Namespaces
Variants

std::ranges:: construct_at

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
定义于头文件 <memory>
调用签名
template < class T, class ... Args >
constexpr T * construct_at ( T * location, Args && ... args ) ;
(C++20 起)

在给定地址 location 处创建以 args 参数初始化的 T 对象。

等价于 if constexpr ( std:: is_array_v < T > )
return :: new ( voidify  ( * location ) ) T [ 1 ] ( ) ;
else
return :: new ( voidify  ( * location ) ) T ( std:: forward < Args > ( args ) ... ) ;
,不同之处在于 construct_at 可用于 常量表达式 的求值中 (C++26 前)

当在常量表达式 expr 的求值过程中调用 construct_at 时, location 必须指向通过 std:: allocator < T > :: allocate 获取的存储空间,或者指向在 expr 求值期间生命周期开始的对象。

此重载仅在满足以下所有条件时参与重载决议:

如果 std:: is_array_v < T > true sizeof... ( Args ) 非零,则程序非良构。

本页面描述的函数式实体是 算法函数对象 (非正式称为 niebloids ),即:

目录

参数

location - 指向未初始化存储位置的指针,将在该位置构造 T 类型对象
args... - 用于初始化的参数

返回值

location

注释

std::ranges::construct_at 的行为与 std::construct_at 完全相同,唯一的区别在于它不会参与实参依赖查找。

示例

#include <iostream>
#include <memory>
struct S
{
    int x;
    float y;
    double z;
    S(int x, float y, double z) : x{x}, y{y}, z{z} { std::cout << "S::S();\n"; }
    ~S() { std::cout << "S::~S();\n"; }
    void print() const
    {
        std::cout << "S { x=" << x << "; y=" << y << "; z=" << z << "; };\n";
    }
};
int main()
{
    alignas(S) unsigned char buf[sizeof(S)];
    S* ptr = std::ranges::construct_at(reinterpret_cast<S*>(buf), 42, 2.71828f, 3.1415);
    ptr->print();
    std::ranges::destroy_at(ptr);
}

输出:

S::S();
S { x=42; y=2.71828; z=3.1415; };
S::~S();

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的C++标准。

缺陷报告 适用范围 发布时行为 正确行为
LWG 3436 C++20 construct_at 无法创建数组类型对象 可对定长数组进行值初始化
LWG 3870 C++20 construct_at 可能创建cv限定类型对象 仅允许cv非限定类型

参见

销毁给定地址处的对象
(算法函数对象)
在给定地址处创建对象
(函数模板)