[2026] C++ Designated Initializers (C++20) | `.field = value` for Aggregates
이 글의 핵심
C++20 designated initializers let you name struct members in brace initialization. Declaration order required; differs from C flexibility. Aggregate-only; compare with list and copy initialization.
What are designated initializers?
Initialize aggregate members by name (C++20), similar to C99 style but with C++ ordering rules. 아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며, 에러 처리를 통해 안정성을 확보합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
struct Point {
int x;
int y;
int z;
};
Point p1 = {1, 2, 3};
Point p2 = {.x = 1, .y = 2, .z = 3};
Point p3 = {.x = 1, .z = 3}; // y value-initialized
// Point p4 = {.z = 3, .x = 1}; // error: out of declaration order
Basic usage
아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
struct Config {
std::string host;
int port;
bool ssl;
int timeout;
};
Config cfg = {
.host = "localhost",
.port = 8080,
.ssl = true,
.timeout = 30
};
Nested structs
다음은 cpp를 활용한 상세한 구현 코드입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
struct Address {
std::string street;
std::string city;
int zip;
};
struct Person {
std::string name;
int age;
Address address;
};
Person p = {
.name = "Alice",
.age = 30,
.address = {
.street = "123 Main St",
.city = "Seoul",
.zip = 12345
}
};
Compared to other styles
| Style | Notes |
|---|---|
Point p{1,2,3} | Short; order-dependent |
Point p{.x=1,...} | Self-documenting; order must match declarations |
Point p(1,2,3) | Requires ctor (non-aggregate) |
| Default member init | Fills omitted members |
| Unlike C, out-of-order designation is not allowed in C++20. |
Performance
Designated initialization is a source-level feature; generated code is typically the same as positional aggregate init.
Common mistakes
- Member order changed in refactor—update all designated lists.
- Type no longer aggregate (added ctor/virtual)—designators disappear.
- Mixing designated and positional in one initializer—follow your compiler’s rules (often disallowed).