Why is sizeof(std::variant) the same size as a struct with the same members?

Viewed 8026

The class template std::variant represents a type-safe union. An instance of std::variant at any given time either holds a value of one of its alternative types, or it holds no value.

sizeof(std::variant<float, int32_t, double>) == 16

But if it is a union, why does it take so much space?

struct T1 {
    float a;
    int32_t b;
    double c;
};

struct T2 {
    union {
        float a;
        int32_t b;
        double c;
    };
};

The variant has the same size as the struct

sizeof(T1) == 16
sizeof(T2) == 8

I would expect the size of the union, plus 4 bytes to store, which type is active.

4 Answers
Related