std::construct_at
来自 cppreference.cn
定义于头文件 <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_unbounded_array_v<T> 为 false。
- ::new(std::declval<void*>()) T(std::declval<Args>()...) 当被视为 未求值操作数 时,格式良好。
如果 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++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 3436 | C++20 | construct_at 无法创建数组类型的对象 |
可以值初始化有界数组 |
LWG 3870 | C++20 | construct_at 可以创建 cv 限定类型的对象 |
仅允许 cv 非限定类型 |
[编辑] 参见
分配未初始化的存储 ( std::allocator<T> 的公共成员函数) | |
[静态] |
在已分配的存储中构造对象 (函数模板) |
(C++17) |
销毁给定地址的对象 (函数模板) |
(C++20) |
在给定地址创建对象 (算法函数对象) |