CPP

[C++] union (DX Matrix)

CGNY 2023. 9. 4. 12:14

이번글은 union 키워드에 대한 간단한 글입니다!

 

union

union이란? A union is a special class type that can hold only one of its non-static data members at a time. 라고 합니다!

해석하면 한번에 하나의 non-static 데이터 멤버를 가질 수 있다고 합니다.

약간 카멜레온을 생각해주시면 될거같습니다. 어쩔때는 A였다가 어쩔때는 B였다가 하는 식으로요(저는 이렇게 이해했습니다)

아니면 키워드 그대로 '연합체'느낌으로 받아 드리셔도 될거같습니다.

 

우리는 하나의 연합체다ㅎㅎ 그래서 메모리도 공유한다.

또한 union은 다른 데이터 멤버중에 가장큰 크기를 가지는 데이터 타입의 크기를 할당받습니다.

 

바로 예시코드를 보면서 이해를 해보도록 하겠습니다.

#include <cstdint>
#include <iostream>
 
union S
{
    std::int32_t n;     // occupies 4 bytes
    std::uint16_t s[2]; // occupies 4 bytes
    std::uint8_t c;     // occupies 1 byte
};                      // the whole union occupies 4 bytes
 
int main()
{
    S s = {0x12345678}; 
    std::cout << std::hex << "s.n = " << s.n << '\n';
    s.s[0] = 0x0011;
    std::cout << "s.c is now " << +s.c << '\n'
              << "s.n is now " << s.n << '\n';
}

// s.n = 12345678
// s.c is now 11
// s.n is now 12340011

위처럼 메모리를 공유하면서 연합체 처럼 사용되고 있습니다.

흥미로운 부분은 s.s[0] = 0x0011; 를 실행하고 나서 가장 아래의 s.n를 16진수 형태로 출력을 하면은 

12340011로 나온다는 점입니다.

(하지만 컴파일러에 따라 다르게 출력 될 수 있으므로 주의하셔야 합니다)

 

DX11 Matrix

MS에서 DX11용 SimpleMath.h의 Matrix 구조체에도 union을 확인할  수 있는데요

(사실 XMFLOAT4X4에 정의되어 있습니다)

이렇게 XMFLOAT4X4를 상속받고 있으며 

 

아래 보이는 것처럼 union으로 데이터 멤버를 정의하고 있습니다.

 

사용을 할때에는 아래처럼 사용할 수 있습니다.

연산자 오버로딩을 한 것을 호출하여 0행0열에 접근할 수 있으며 (_11과 같습니다)

아니면 '.' 연산자를 통해서도 똑같이 0행 0열(수학적으로는 1행1열)에 접근이 똑같이 가능합니다.


참고한 자료

https://en.cppreference.com/w/cpp/language/union

 

Union declaration - cppreference.com

A union is a special class type that can hold only one of its non-static data members at a time. [edit] Syntax The class specifier for a union declaration is similar to class or struct declaration: union attr class-head-name { member-specification } attr -

en.cppreference.com