Struct이랑 Union이랑 비슷한 개념이면서도 다른게 Union의 경우 배열의 크기를 상대적으로 Struct보다 작게 사용할 수 있다.
#include <iostream>
using namespace std;
int main()
{
struct Product0
{
int idType; // 4 bytes
int idInteger; // 4 bytes
int idChars[10]; // 10 x 4 = 40 bytes (int 배열)
};
cout << sizeof(Product0) << endl; // 결과: 48 (정렬 포함)
return 0;
}
구조체 Product0은 고정된 형식으로 데이터를 저장합니다. int 타입 기준으로 정렬이 되며, 배열 크기만큼의 메모리를 항상 차지한다.
union을 활용한 메모리 절약
union은 여러 타입을 하나의 공간에서 공유합니다. 위 예시에서 ID는 가장 큰 멤버인 chars 기준으로 10 바이트를 사용한다.
union ID
{
int integer; // 4 bytes
char chars[10]; // 10 bytes
};
cout << sizeof(ID) << endl; // 출력: 10 (또는 정렬에 따라 더 클 수 있음)
union을 포함한 구조체 정의
struct Product1
{
int idType; // 4 bytes
ID id; // 10 bytes (chars 기준)
};
Product1은 idType(4바이트)와 union ID(10바이트)로 구성되지만, 정렬 기준(4의 배수)에 따라 전체 크기는 16 바이트가 된다.
cout << sizeof(Product1) << endl; // 출력: 16
union 사용 예시 코드
union을 사용할 경우 같은 메모리 공간을 공유하기 때문에 마지막에 저장된 값만 유지된다.
Product0 product = {0, 12}; // idType = 0, 정수 ID 사용
if (product.idType == 0)
cout << product.idInteger << endl;
else
cout << product.idChars << endl;
// 만약에 product ID가 이제 char와 정수를 모두 왔다갔다해야할 경우
Product1 product1 = {1, {.chars = "abc"}};
if (product1.idType == 0)
cout << product1.id.integer << endl;
else
cout << product1.id.chars << endl;
'C++' 카테고리의 다른 글
[C++] Array (0) | 2025.05.29 |
---|---|
[C++] enum class & enum struct (0) | 2025.05.28 |
[C++] enum (0) | 2025.05.27 |
[C++] Struct alignas (0) | 2025.05.24 |
[C++] Struct 구조체 (0) | 2025.05.23 |