std::ranges::construct_at
来自 zh.cppreference.net
| 定义于头文件 <memory>
|
||
| 调用签名 |
||
template< class T, class... Args >
constexpr T* construct_at( T* location, Args&&... args );
|
(始于 C++20) | |
在给定地址 T 处创建以 args 中的参数初始化的 location 对象。
等价于
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)。
当 construct_at 在某常量表达式 expr 的求值中被调用时,location 必须指向由 std::allocator<T>::allocate 获得的存储,或者其生命周期在该求值 expr 内开始的对象。
此重载仅在满足所有以下条件时参与重载决议:
std::is_unbounded_array_v<T>是false。::new(std::declval<void*>()) T(std::declval<Args>()...)作为非求值操作数处理时是良构的。
如果 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++ 标准。
| DR | 应用于 | 公布的行为 | 正确行为 |
|---|---|---|---|
| LWG 3436 | C++20 | construct_at 无法创建数组类型对象
|
可以对有界数组进行值初始化 |
另见
(C++20) |
销毁给定地址处的对象 (算法函数对象) |
(C++20) |
在给定地址处创建对象 (函数模板) |