跳到主要内容

std::construct_at() 算法

// (1)
template< class T, class... Args >
constexpr T* construct_at( T* p, Args&&... args );

在给定地址 p 处创建一个用参数 args... 初始化的 T 对象。

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

除了 construct_at 可以用于评估常量表达式

当在某个常量表达式 e 的评估中调用 construct_at 时,参数 p 必须指向通过 std::allocator<T>::allocate 获得的存储空间,或者指向其生命周期在 e 评估中开始的对象。

重载解析

仅当 ::new(std::declval<void*>()) T(std::declval<Args>()...) 在未求值上下文中格式正确时,才参与重载解析。

参数

p

指向将在其上构造 T 对象的未初始化存储的指针。

args..

用于初始化对象的参数。

返回值

p

(无)

复杂度

O(1)

异常

(无)

示例

Main.cpp
#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();
本文档源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”可查看对本文档进行的所有更改。
悬停查看原始许可证。

std::construct_at() 算法

// (1)
template< class T, class... Args >
constexpr T* construct_at( T* p, Args&&... args );

在给定地址 p 处创建一个用参数 args... 初始化的 T 对象。

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

除了 construct_at 可以用于评估常量表达式

当在某个常量表达式 e 的评估中调用 construct_at 时,参数 p 必须指向通过 std::allocator<T>::allocate 获得的存储空间,或者指向其生命周期在 e 评估中开始的对象。

重载解析

仅当 ::new(std::declval<void*>()) T(std::declval<Args>()...) 在未求值上下文中格式正确时,才参与重载解析。

参数

p

指向将在其上构造 T 对象的未初始化存储的指针。

args..

用于初始化对象的参数。

返回值

p

(无)

复杂度

O(1)

异常

(无)

示例

Main.cpp
#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();
本文档源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”可查看对本文档进行的所有更改。
悬停查看原始许可证。