std::construct_at() 算法
- 自 C++20 起
// (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 | 指向将构造 |
args.. | 用于初始化对象的参数。 |
返回值
p
(无)
复杂度
O(1)
异常
(无)
可能的实现
ranges::construct_at(1)
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
完全相同,只是它对参数依赖查找不可见。
示例
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 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();