본문으로 건너뛰기 C++20 Designated Initializers Complete Guide

C++20 Designated Initializers Complete Guide

C++20 Designated Initializers Complete Guide

이 글의 핵심

C++20 Designated Initializers: clear struct initialization. What are Designated Initializers? Why needed and basic syntax as axes, explaining syntax, patterns, and precautions with examples.

What are Designated Initializers? Why Needed?

Problem Scenario: Confusion in Struct Initialization

Problem: When struct has many members, listing values in order makes it unclear which value belongs to which member.

struct Config {
    std::string host;
    int port;
    bool ssl;
    int timeout;
    int max_connections;
};
int main() {
    // Unclear which value is which member
    Config cfg = {"localhost", 8080, true, 30, 100};
    // Is port 8080? Is timeout 30?
}

Solution: Designated Initializers (C++20) initialize by specifying member names. Code becomes clear and safe even when member order changes.

int main() {
    Config cfg = {
        .host = "localhost",
        .port = 8080,
        .ssl = true,
        .timeout = 30,
        .max_connections = 100
    };
    // Clear and readable!
}

1. Basic Syntax

Basic Usage

struct Point {
    int x;
    int y;
};
int main() {
    // C++20 Designated Initializers
    Point p1 = {.x = 10, .y = 20};
    
    // Can omit braces
    Point p2{.x = 30, .y = 40};
    
    std::cout << p1.x << ", " << p1.y << '\n';  // 10, 20
}

Comparison with Regular Initialization

struct Person {
    std::string name;
    int age;
    std::string city;
};
int main() {
    // Regular initialization (order matters)
    Person p1 = {"Alice", 30, "Seoul"};
    
    // Designated Initializers (specify member names)
    Person p2 = {
        .name = "Bob",
        .age = 25,
        .city = "Busan"
    };
}

2. Order Rules

Declaration Order Must Be Maintained

In C++20, Designated Initializers must follow declaration order (different from C).

struct Data {
    int a;
    int b;
    int c;
};
int main() {
    // ✅ In declaration order
    Data d1 = {.a = 1, .b = 2, .c = 3};  // OK
    
    // ❌ Order violation
    // Data d2 = {.b = 2, .a = 1, .c = 3};  // Error in C++20
    
    // ✅ Skipping is OK
    Data d3 = {.a = 1, .c = 3};  // b = 0 (default value)
}

C vs C++20 Difference

ItemCC++20
OrderFreeDeclaration order required
MixingAllowedNot allowed
ArrayFree indexSequential only
// OK in C
struct Data { int a, b, c; };
Data d = {.c = 3, .a = 1, .b = 2};  // C: OK, C++20: Error

3. Nested Structs

Nested Initialization

struct Address {
    std::string city;
    std::string street;
    int zipcode;
};
struct Employee {
    std::string name;
    int id;
    Address address;
};
int main() {
    Employee emp = {
        .name = "Alice",
        .id = 1001,
        .address = {
            .city = "Seoul",
            .street = "Gangnam",
            .zipcode = 12345
        }
    };
    
    std::cout << emp.name << ", " << emp.address.city << '\n';
}

4. Default Values and Partial Initialization

Partial Initialization

struct Config {
    std::string host = "localhost";
    int port = 8080;
    bool ssl = false;
    int timeout = 30;
};
int main() {
    // Only specify some members
    Config cfg1 = {.port = 9000};
    // host="localhost", port=9000, ssl=false, timeout=30
    
    Config cfg2 = {.host = "example.com", .ssl = true};
    // host="example.com", port=8080, ssl=true, timeout=30
}

Zero Initialization

struct Data {
    int a;
    int b;
    int c;
};
int main() {
    // Unspecified members are zero-initialized
    Data d = {.a = 10};  // a=10, b=0, c=0
}

Summary

Key Points

  1. Designated Initializers: C++20 feature for clear initialization
  2. Syntax: .member = value format
  3. Order: Must follow declaration order
  4. Partial: Unspecified members use default/zero
  5. Nested: Can nest for complex structures

When to Use

Use Designated Initializers when:

  • Struct has many members
  • Want clear, self-documenting code
  • Need to skip some members
  • Initializing config/option structs ❌ Don’t use when:
  • C++17 or earlier (not supported)
  • Need out-of-order initialization
  • Working with non-aggregate types

Best Practices

  • ✅ Use for config/option structs
  • ✅ Provide default values for optional members
  • ✅ Follow declaration order
  • ❌ Don’t mix with positional initialization
  • ❌ Don’t use with non-aggregate types


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. C++20 Designated Initializers complete guide: clear struct initialization. What are Designated Initializers? Why needed … 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, initializer, cpp20, struct, syntax, aggregate 등으로 검색하시면 이 글이 도움이 됩니다.