Namespaces
Variants

std::construct_at

来自 zh.cppreference.net
 
 
算法库
受约束算法和范围算法 (C++20)
受约束算法,例如 ranges::copy, ranges::sort, ...
排序及相关操作
划分操作
(C++11)    

排序操作
二分搜索操作
(在已划分的范围上)
集合操作(在已排序的范围上)
合并操作(在已排序的范围上)
堆操作
最小/最大操作
(C++11)
(C++17)
字典序比较操作
排列操作


 
 
定义于头文件 <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) 非零,则程序非良构。

参数

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 无法创建数组类型的对象 可以值初始化有界数组

参见

分配未初始化的存储空间
( std::allocator<T> 的公开成员函数)
[static]
在分配的存储空间中构造对象
(函数模板)
(C++17)
销毁给定地址的对象
(函数模板)
在给定地址创建对象
(算法函数对象)