我想知道std::variant
的实现是否必须“平坦”或是否允许为其成员动态分配内存,这样一系列变体会退化为一系列指针,从而破坏缓存局部性。
No, very explicitly. From [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 ofvariant
holds a value of alternative typeT
, it means that a value of typeT
, referred to as the variant object's contained value, is allocated within the storage of thevariant
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 thevariant
storage suitably aligned for all types inTypes...
. It is implementation-defined whether over-aligned types are supported.
According to cppreference ::std::variant
must not allocate dynamic memory.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.