C++ Aggregate Initialization 완벽 가이드 | 집합 초기화

C++ Aggregate Initialization 완벽 가이드 | 집합 초기화

이 글의 핵심

C++ Aggregate Initialization 완벽 가이드에 대한 실전 가이드입니다. 집합 초기화 등을 예제와 함께 상세히 설명합니다.

Aggregate Initialization이란? 왜 중요한가

문제 시나리오: 간단한 구조체에 생성자가 필요한가

문제: 데이터만 담는 간단한 구조체에 생성자를 일일이 작성하면 보일러플레이트가 늘어납니다.

struct Point {
    int x;
    int y;
    
    // 생성자 필요?
    Point(int x, int y) : x(x), y(y) {}
};

int main() {
    Point p(10, 20);
}

해결: Aggregate 타입은 생성자 없이 중괄호 초기화로 간단히 만들 수 있습니다.

struct Point {
    int x;
    int y;
    // 생성자 불필요
};

int main() {
    Point p = {10, 20};  // 간단!
}

목차

  1. Aggregate 타입 조건
  2. 기본 초기화 문법
  3. C++17/20 변경사항
  4. 배열 초기화
  5. 자주 발생하는 문제와 해결법
  6. 프로덕션 패턴
  7. 완전한 예제

1. Aggregate 타입 조건

C++17 Aggregate 조건

  • 배열, 또는
  • 클래스/구조체:
    • 사용자 정의 생성자 없음 (default/delete는 OK)
    • private/protected 비정적 멤버 없음
    • 가상 함수 없음
    • 가상/private/protected 베이스 클래스 없음
// ✅ Aggregate
struct Point {
    int x;
    int y;
};

// ✅ Aggregate (C++17+, 베이스 클래스 OK)
struct Base {
    int a;
};

struct Derived : Base {
    int b;
};

// ❌ Not Aggregate (생성자 있음)
struct NotAgg1 {
    NotAgg1(int x) : value(x) {}
    int value;
};

// ❌ Not Aggregate (private 멤버)
struct NotAgg2 {
private:
    int x;
public:
    int y;
};

// ❌ Not Aggregate (가상 함수)
struct NotAgg3 {
    virtual void func() {}
    int x;
};

타입 체크

#include <type_traits>

struct Agg { int x, y; };
struct NotAgg { NotAgg(int x) : value(x) {} int value; };

int main() {
    static_assert(std::is_aggregate_v<Agg>);      // true
    static_assert(!std::is_aggregate_v<NotAgg>);  // true
}

2. 기본 초기화 문법

구조체 초기화

struct Person {
    std::string name;
    int age;
    double height;
};

int main() {
    // 모든 멤버 초기화
    Person p1 = {"Alice", 30, 165.5};
    
    // 일부 멤버 (나머지 기본값)
    Person p2 = {"Bob", 25};  // height = 0.0
    
    // 빈 초기화
    Person p3 = {};  // name = "", age = 0, height = 0.0
    
    // C++11 uniform initialization
    Person p4{"Charlie", 35, 180.0};
}

중첩 구조체

struct Address {
    std::string city;
    int zipcode;
};

struct Employee {
    std::string name;
    int id;
    Address address;
};

int main() {
    Employee emp = {
        "Alice",
        100,
        {"Seoul", 12345}
    };
    
    std::cout << emp.address.city << '\n';  // Seoul
}

3. C++17/20 변경사항

C++17: 베이스 클래스 허용

struct Base {
    int a;
};

struct Derived : Base {
    int b;
};

int main() {
    // C++17+: 베이스 클래스가 있어도 Aggregate
    Derived d = {{10}, 20};  // a = 10, b = 20
}

C++20: Designated Initializers

struct Point {
    int x;
    int y;
    int z;
};

int main() {
    // C++20: 멤버 이름 지정
    Point p = {
        .x = 10,
        .y = 20,
        .z = 30
    };
}

4. 배열 초기화

1차원 배열

int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5] = {1, 2};  // {1, 2, 0, 0, 0}
int arr3[] = {1, 2, 3};  // 크기 자동 (3)

2차원 배열

int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};

// 평탄화 가능
int matrix2[2][3] = {1, 2, 3, 4, 5, 6};

구조체 배열

struct Point { int x, y; };

Point points[3] = {
    {0, 0},
    {10, 20},
    {30, 40}
};

// C++20 Designated
Point points2[2] = {
    {.x = 0, .y = 0},
    {.x = 10, .y = 20}
};

5. 자주 발생하는 문제와 해결법

문제 1: 생성자가 있는 클래스

증상: error: no matching constructor.

// ❌ 생성자 있음
struct NotAggregate {
    NotAggregate(int x) : value(x) {}
    int value;
};

// NotAggregate obj = {10};  // Error

// ✅ 생성자 없음
struct Aggregate {
    int value;
};

Aggregate obj = {10};  // OK

문제 2: private 멤버

// ❌ private 멤버
struct NotAggregate {
private:
    int x;
public:
    int y;
};

// NotAggregate obj = {1, 2};  // Error

// ✅ 모두 public
struct Aggregate {
    int x;
    int y;
};

Aggregate obj = {1, 2};  // OK

문제 3: 초기화 개수 초과

struct Point {
    int x;
    int y;
};

int main() {
    Point p1 = {1, 2};     // OK
    // Point p2 = {1, 2, 3};  // Error: 멤버가 2개인데 3개 제공
}

문제 4: 상속과 Aggregate

struct Base {
    int a;
};

// ✅ public 상속
struct Derived1 : Base {
    int b;
};

Derived1 d1 = {{10}, 20};  // OK

// ❌ private 상속
struct Derived2 : private Base {
    int b;
};

// Derived2 d2 = {{10}, 20};  // Error

6. 프로덕션 패턴

패턴 1: 설정 구조체

struct DatabaseConfig {
    std::string host = "localhost";
    int port = 5432;
    std::string database = "mydb";
    std::string user = "admin";
    std::string password;
    int connection_pool_size = 10;
};

DatabaseConfig prod_config = {
    .host = "prod.example.com",
    .port = 5432,
    .database = "production",
    .user = "app_user",
    .password = "secret",
    .connection_pool_size = 100
};

패턴 2: 테스트 픽스처

struct TestData {
    int input;
    int expected;
    std::string description;
};

std::vector<TestData> test_cases = {
    {0, 0, "zero"},
    {1, 1, "one"},
    {5, 25, "five squared"},
    {-3, 9, "negative squared"}
};

for (const auto& test : test_cases) {
    int result = square(test.input);
    assert(result == test.expected);
}

정리

개념설명
Aggregate생성자 없는 단순 타입
초기화중괄호 {} 사용
조건생성자 없음, public 멤버, 가상 함수 없음
C++17베이스 클래스 허용
C++20Designated Initializers 추가

Aggregate Initialization은 간단한 데이터 구조보일러플레이트 없이 초기화하는 C++의 기본 기능입니다.


FAQ

Q1: Aggregate란?

A: 생성자가 없고, 모든 멤버가 public인 단순 타입입니다. 배열, 구조체 등이 해당됩니다.

Q2: POD와 차이는?

A: POD(Plain Old Data)는 Aggregate + trivial 조건을 만족하는 타입입니다. Aggregate가 더 넓은 개념입니다.

Q3: 일부만 초기화하면?

A: 나머지는 기본값 또는 0으로 초기화됩니다.

Q4: C++17 변경사항은?

A: C++17부터 베이스 클래스가 있어도 Aggregate가 될 수 있습니다.

Q5: C++20 변경사항은?

A: Designated Initializers가 추가되어 멤버 이름으로 초기화할 수 있습니다.

Q6: Aggregate 학습 리소스는?

A:

한 줄 요약: Aggregate Initialization으로 간단한 구조체를 보일러플레이트 없이 초기화할 수 있습니다. 다음으로 Initialization Order를 읽어보면 좋습니다.


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

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

  • C++20 Designated Initializers 완벽 가이드 | 명확한 구조체 초기화
  • C++ 균일 초기화 | “Uniform Initialization” 가이드
  • C++ Value Initialization | “값 초기화” 가이드

관련 글

  • C++ Aggregate Initialization |
  • C++ struct vs class |
  • C++20 Designated Initializers 완벽 가이드 | 명확한 구조체 초기화
  • C++ call_once |
  • C++ 배열 vs vector |