Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr inside a variant. Is it safe to use?

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.

like image 930
Juan JuezSarmiento Avatar asked Sep 12 '25 20:09

Juan JuezSarmiento


1 Answers

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.

like image 172
Raildex Avatar answered Sep 15 '25 11:09

Raildex