std::ranges::construct_at
来自cppreference.com
| 定义于头文件 <memory>
|
||
| 调用签名 |
||
| template< class T, class... Args > constexpr T* construct_at( T* p, Args&&... args ); |
(C++20 起) | |
在给定地址 p 创建以参数 args... 初始化的 T 对象。 construct_at 仅若 ::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 的求值内的对象。
此页面上描述的仿函数实体是 niebloid ,即:
实际上,它们能以函数对象,或以某些特殊编译器扩展实现。
参数
| p | - | 指向将在其上构造 T 对象的未初始化存储的指针
|
| args... | - | 用于初始化的参数 |
返回值
p
可能的实现
struct construct_at_fn { template<class T, class...Args> requires requires (void* vp, Args&&... args) { ::new (vp) T(static_cast<Args&&>(args)...); } constexpr T* operator()(T* p, Args&&... args) const { return std::construct_at(p, static_cast<Args&&>(args)...); } }; inline constexpr construct_at_fn construct_at{}; |
注解
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++20) |
销毁位于给定地址的元素 (niebloid) |
| (C++20) |
在给定地址创建对象 (函数模板) |