std::construct_at

< cpp‎ | memory
定义于头文件 <memory>
template<class T, class... Args>
constexpr T* construct_at( T* p, Args&&... args );
(C++20 起)

在给定地址 p 创建以参数 args... 初始化的 T 对象。此函数模板的特化仅若 ::new(std::declval<void*>()) T(std::declval<Args>()...) 在不求值语境中为良构才参与重载决议。

等价于

return ::new (const_cast<void*>(static_cast<const volatile void*>(p)))
    T(std::forward<Args>(args)...);

除了 construct_at 可用于常量表达式的求值。

在某常量表达式 e 的求值中调用 construct_at 时,参数 p 必须指向用 std::allocator<T>::allocate 获得的存储或生存期始于 e 的求值内的对象。

参数

p - 指向将在其上构造 T 对象的未初始化存储的指针
args... - 用于初始化的参数

返回值

p

示例

#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 storage[sizeof(S)];
 
    S* ptr = std::construct_at(reinterpret_cast<S*>(storage), 42, 2.71828f, 3.1415);
    ptr->print();
 
    std::destroy_at(ptr);
}

输出:

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

参阅

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