Id like to ask, is safe having a variant like this?
struct A
{
unique_ptr<T> anything;
};
struct B
{
int x = 0;
int y = 0;
};
variant<A, B> myVar;
myVar = ... A object;
myVar = ... B object;
myVar = ... another A object;
Would the std::unique_ptr
destructor be invoked for all compilers? The idea would be to create an std::array
of variant<A, B>
to use it in a FIFO. It seems working fine here in Visual Studio, but I ask because I read this from cppreference.com/variant, and I'm not sure if I understood it fully:
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 paragraph you quoted is a guarantee by the standard;
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.
It means std::variant
is not allowed to utilize dynamic allocation for the objects that the variant holds. It's a guarantee by the standard.
If you have a variant object with Foo
, Foo
is in the memory of the variant and not in a dynamically allocated object somewhere else.
Which means it is safe to use dynamic allocation (i.e. unique_ptr
) within a variant. All destructors are properly called when they need to be called.
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