Namespaces
Variants

std:: 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 ) 非零,则程序非良构。

目录

参数

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

返回值

location

示例

#include <bit>
#include <memory>
class S
{
    int x_;
    float y_;
    double z_;
public:
    constexpr S(int x, float y, double z) : x_{x}, y_{y}, z_{z} {}
    [[nodiscard("no side-effects!")]]
    constexpr bool operator==(const S&) const noexcept = default;
};
consteval bool test()
{
    alignas(S) unsigned char storage[sizeof(S)]{};
    S uninitialized = std::bit_cast<S>(storage);
    std::destroy_at(&uninitialized);
    S* ptr = std::construct_at(std::addressof(uninitialized), 42, 2.71f, 3.14);
    const bool res{*ptr == S{42, 2.71f, 3.14}};
    std::destroy_at(ptr);
    return res;
}
static_assert(test());
int main() {}

缺陷报告

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

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

参见

分配未初始化的存储空间
( std::allocator<T> 的公开成员函数)
[static]
在分配的存储空间中构造对象
(函数模板)
(C++17)
销毁给定地址的对象
(函数模板)
在给定地址创建对象
(算法函数对象)