I was wondering if an implementation of std::variant
must necessarily be "flat" or whether it is allowed to dynamically allocate memory for its members, such that a sequence of variants would degenerate to a sequence of pointers, thereby destroying cache locality.
std::variant (C++17)A std::variant is a type-safe union. An instance of std::variant has a value from one of its types. The value must not be a reference, C-array or void. A std::variant can have one type more than once.
It holds one of several alternatives in a type-safe way. No extra memory allocation is needed. The variant needs the size of the max of the sizes of the alternatives, plus some little extra space for knowing the currently active value. By default, it initializes with the default value of the first alternative.
Inside every std::string is a dynamically allocated array of char .
std::function can store objects of arbitrary size, this means it must perform dynamic memory allocation in some cases. there are certain types for which std::function is guaranteed not to throw exceptions. This implies that there are certain types it must store without dynamic memory allocation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With