|
| 1 | +# constexpr配置new [P2747R2] |
| 2 | +* cpp26[meta cpp] |
| 3 | + |
| 4 | +<!-- start lang caution --> |
| 5 | + |
| 6 | +このページはC++26に採用される見込みの言語機能の変更を解説しています。 |
| 7 | + |
| 8 | +のちのC++規格でさらに変更される場合があるため[関連項目](#relative-page)を参照してください。 |
| 9 | + |
| 10 | +<!-- last lang caution --> |
| 11 | + |
| 12 | +## 概要 |
| 13 | +C++26では、配置`new`構文を定数式の文脈で使用できるようになる。 |
| 14 | + |
| 15 | +```cpp |
| 16 | +template <class T, class... Args> |
| 17 | +constexpr void f(T* p, Args... args) { |
| 18 | + new (p) T(args...); // C++26: OK |
| 19 | +} |
| 20 | +``` |
| 21 | +
|
| 22 | +C++20では、[`std::construct_at()`](/reference/memory/construct_at.md)関数が導入された。この関数には`constexpr`がついており、コンパイラが特別扱いすることによって、コンパイル時に配置`new`相当のことができた。 |
| 23 | +
|
| 24 | +しかし、配置`new`構文と[`std::construct_at()`](/reference/memory/construct_at.md)では、できることに大きな差がある。 |
| 25 | +
|
| 26 | +| 操作 | 配置`new` | `std::construct_at()` | |
| 27 | +|------|-----------|-----------------------| |
| 28 | +| 値初期化 | `new (p) T(args...)` | `std::construct_at(p, args...)` | |
| 29 | +| デフォルト初期化 | `new (p) T` | できない。`std::default_construct_at()`が提案されている | |
| 30 | +| リスト初期化 | `new (p) T{a, b}` | できない | |
| 31 | +| 指示付き初期化 | `new (p) T{.a=a, .b=b}` | できない。関数で表現する方法が現状ない | |
| 32 | +
|
| 33 | +これらの表現力の違いから、配置`new`構文自体が`constexpr`内で使用できることとなった。 |
| 34 | +
|
| 35 | +関連して、[`<new>`](/reference/new.md)ライブラリの配置`new`演算子もまた、`constexpr`に対応する |
| 36 | +
|
| 37 | +
|
| 38 | +## <a id="relative-page" href="#relative-page">関連項目</a> |
| 39 | +- [C++11 constexpr](/lang/cpp11/constexpr.md) |
| 40 | +- [`new`演算子](/reference/new/op_new.md) |
| 41 | +- [`new[]`演算子](/reference/new/op_new[].md) |
| 42 | +
|
| 43 | +
|
| 44 | +## 参照 |
| 45 | +- [P2747R2 constexpr placement new](https://open-std.org/jtc1/sc22/wg21/docs/papers/2024/p2747r2.html) |
0 commit comments