std::construct_at
来自cppreference.com
| 在标头 <memory> 定义
|
||
| |
(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("无副作用!")]]
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 限定的类型 |
