std::variant 是否允许为其成员分配内存?

Is std::variant allowed to allocate memory for its members?

我想知道 std::variant 的实现是否一定是 "flat" 或者是否允许它为其成员动态分配内存,这样一个变体序列就会退化为一个序列指针,从而破坏缓存局部性。

根据 cppreference ::std::variant 不能分配动态内存。

As with unions, if a variant holds a value of some object type T, the object representation of T is allocated directly within the object representation of the variant itself. Variant is not allowed to allocate additional (dynamic) memory.

不,非常明确。来自 [variant.variant]:

Any instance of variant at any given time either holds a value of one of its alternative types, or it holds no value. When an instance of variant holds a value of alternative type T, it means that a value of type T, referred to as the variant object's contained value, is allocated within the storage of the variant object. Implementations are not permitted to use additional storage, such as dynamic memory, to allocate the contained value. The contained value shall be allocated in a region of the variant storage suitably aligned for all types in Types.... It is implementation-defined whether over-aligned types are supported.