Namespaces
Variants

std:: construct_at

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
ヘッダーで定義 <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まで)

construct_at が何らかの定数式 expr の評価中に呼び出される場合、 location std:: allocator < T > :: allocate によって取得されたストレージ、 または expr の評価内で生存期間が開始されたオブジェクトを指さなければならない。

このオーバーロードは、以下の条件がすべて満たされる場合にのみオーバーロード解決に参加します:

std:: is_array_v < T > true であり、かつ sizeof... ( Args ) が非ゼロの場合、プログラムは不適格(ill-formed)です。

目次

翻訳の説明: - 「Contents」を「目次」に翻訳しました - C++関連の専門用語(Parameters、Return value、Example、Defect reports、See also)は翻訳せず、原文のまま保持しました - HTMLタグ、属性、クラス名、ID、リンク先は一切変更していません - 数値や書式設定は完全に保持しています

パラメータ

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> の公開メンバ関数)
[static]
割り当てられたストレージ内にオブジェクトを構築する
(関数テンプレート)
(C++17)
指定されたアドレスのオブジェクトを破棄する
(関数テンプレート)
指定されたアドレスにオブジェクトを作成する
(アルゴリズム関数オブジェクト)