C++ Designated Initializers (C++20) | `.field = value` for Aggregates
이 글의 핵심
Designated initializers use `.member = value` for aggregates in C++20. Improves readability for large option structs; order must match declarations.
What are designated initializers?
Initialize aggregate members by name (C++20), similar to C99 style but with C++ ordering rules.
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
struct Config {
std::string host;
int port;
bool ssl;
int timeout;
};
Config cfg = {
.host = "localhost",
.port = 8080,
.ssl = true,
.timeout = 30
};
Nested structs
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).
FAQ
Q1: When to use?
A: Large config structs, tests, protocols where names beat position.
Q2: Only aggregates?
A: Yes—classes with private data or user ctors need different APIs.
Related: Aggregate initialization, List initialization.
Related posts
- C++ designated initializer (guide)
- C++ Three-way comparison
Keywords
C++, designated initializers, C++20, aggregate initialization, struct.
More links
- C++ Aggregate initialization