问题描述
类模板 std :: variant
表示类型安全的联合。 std :: variant
的实例在任何给定时间要么具有其替代类型之一的值,要么不具有任何值。
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;
};
};
变量的大小与结构相同
sizeof(T1) == 16
sizeof(T2) == 8
我希望联合的大小加上要存储的4个字节(该类型是活动的)。
I would expect the size of the union, plus 4 bytes to store, which type is active.
推荐答案
此处,在变量
中具有最大对齐方式的类型是 double
,对齐方式为8。这意味着整个 variant
必须对齐方式为8。这也意味着其大小必须为8的倍数,以确保数组中每个 variant
的 double
均应对齐8。
Here the type with the largest alignment in the variant
is double
, with an alignment of 8. This means the entire variant
must have an alignment of 8. This also means its size must be a multiple of 8, ensuring that in an array each variant
will have its double
aligned by 8.
但是一个变体不仅要存储最大的类型,还必须存储一个标识符或标记,以了解当前实例化的类型。因此,即使仅将1个字节用于该标识符,整个结构也会填充为16,因此它是8的倍数。
But a variant must store more than just the largest type: it must also store an identifier or tag to know which type is currently instantiated. So even if only 1 byte is used for that identifier, the structure as a whole is padded to 16 so that it is a multiple of 8 in size.
更正确比较如下:
struct
{
union
{
float a;
int32_t b;
double c;
};
int identifier;
};
这篇关于为什么sizeof(std :: variant)的大小与具有相同成员的结构的大小相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!