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

Why is my struct destructed twice with `std::variant` and `std::monostate`?

I am trying to learn std::variant. I do not understand why in this example, where I prefer not to initialize ab yet, and I use std::monostate for that, the class A gets constructed once, but destructed twice. What is happening?

#include <iostream>
#include <variant>

struct A
{
    A() { std::cout << "Constructing A\n"; }
    ~A() { std::cout << "Destructing A\n"; }
};


struct B
{
    B() { std::cout << "Constructing B\n"; }
    ~B() { std::cout << "Destructing B\n"; }
};


int main()
{
    std::variant<std::monostate, A, B> ab;
    ab = A();
}

Running this example gives the output below.

Constructing A
Destructing A
Destructing A

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 :

This line:

ab = A();

Is creating a temporary A object, and then moving it into ab.
You can observe this by adding copy/move constructors and assignment operators:

#include <iostream>
#include <variant>

struct A
{
    A() { std::cout << "Constructing A\n"; }
    A(A const &) { std::cout << "Copy constructing A\n"; }
    A(A &&) { std::cout << "Move constructing A\n"; }
    A& operator=(A const&) { std::cout << "Copy assignment A\n"; return *this; }
    A& operator=(A&&) { std::cout << "Move assignment A\n"; return *this; }
    ~A() { std::cout << "Destructing A\n"; }
};

struct B
{
    B() { std::cout << "Constructing B\n"; }
    ~B() { std::cout << "Destructing B\n"; }
};

int main()
{
    std::variant<std::monostate, A, B> ab;
    ab = A();
}

Output:

Constructing A
Move constructing A
Destructing A
Destructing A

You can avoid the copy/move, by using std::variant::emplace.
If you replace the above mentioned line with:

ab.emplace<A>();

The output should become:

Constructing A
Destructing A
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