Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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> object;
};
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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading