본문 바로가기

C

c++ Union, Variant

Union은 메모리 세이빙에 좋다.

하지만 Union은 개발자가 신경써야 하는 부분이 많기 때문에

아주 조심히 사용해야 한다. 즉, std::variant를 쓰는 것이 안전하다

std::variant는 type tracking이 매번 type을 체크하기 때문에 내부적으로

type을 체크하는 변수가 들어간다. 따라서 overhead가 발생할 수 있다.

std::variant는 하나의 공간 안에 다양한 타입을 안전하게 넣어줄 수 있다.

 

 

코드 >>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
#include <vector>
#include <string>
#include <variant>
#include <vector>
 
// Union은 메모리 세이빙에 좋다
// Union은 개발자가 신경써야 되는 부분이 많기 때문에
// 아주 조심히 사용해야 한다. -> std::variant를 쓰는 것이 안전하다
// std::variant는 type tracking이 들어가며 매번 type을 체크하기 때문에
// overhead가 걸리는 것이 사실이다
//std::variant는 하나의 공간 안에 다양한 타입을 안전하게 넣어줄 수 있다.
template<typename ErrorCode>
std::variant<int, ErrorCode> divide(int a, int b)
{
    if (b == 0)
    {
        return ErrorCode
    }
 
    return a / b;
}
 
struct S // 4+(4)+8 => 16
{
    int i;
    double d;
    float f;
};
 
union U // 8 (double 이 들어가거나 int가 들어가거나)
    // 하나의 타입만 사용이 가능하다는 뜻이다.
{
    int i; //4
    double d; //8
    float f;
};
 
// type tracking
// union-like class/ tagged union
union SV
{
    std::string str;
    std::vector<int> vec;
    ~SV() {}
};
 
int main()
{
    std::cout << "size of S : " << sizeof(S) << std::endl;
    std::cout << "size of U : " << sizeof(U) << std::endl;
 
    U u;
    u.i = 10;
    std::cout << u.i << std::endl// 10
    std::cout << "size of u : " << sizeof(u) << std::endl;
 
    u.d = 0.3// 처음에 들어갔던 int가 없어짐
    std::cout << u.d << std::endl//0.3
    std::cout << "size of u : " << sizeof(u) << std::endl;
 
    //undefiend behavior임
    std::cout << u.i << std::endl// int로 접근 또 한 가능
 
    SV sv = { "Hello, world" };
    std::cout << "sv.str = " << sv.str << '\n';
 
    sv.str.~basic_string();
    new (&sv.vec) std::vector<int>;
    // now, sv.vec is the active member of the union
    std::cout << sv.vec.size() << '\n';
    sv.vec.~vector();
 
    // std::variant
    std::variant<intdoublefloat> v; // 데이터 타입을 추적하는 것 있음
    std::cout << "S:" << sizeof(S) << std::endl;
    std::cout << "U:" << sizeof(U) << std::endl// 8bytes, float을 넣는다고 size 증가 x
    std::cout << "V:" << sizeof(v) << std::endl// 16bytes, float을 넣는다고 size 증가 x
    
    v = 10// int값 입력
    if (auto pVal = std::get_if<double>(&v)) // 만약 v가 double type이라면
    {
        std::cout << *pVal << std::endl;
    }
    else
    {
        std::cout << "v is not type double" << std::endl;
    }
 
    v = 10.0// double 입력
    if (auto pVal = std::get_if<double>(&v)) // 만약 v가 double type이라면
    {
        std::cout << *pVal << std::endl;
    }
    else
    {
        std::cout << "v is not type double" << std::endl;
    }
 
    // std variant를 사용해서 쉽게 string에서 vector로 정의 가능하다
 
    std::variant<std::stringstd::vector<int>> sv1;
    sv1 = std::string("abcdef");
    std::cout << std::get<std::string>(sv1) << std::endl;
 
    sv1 = std::vector1,2,3 };
 
 
 
    return 0;
}