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
ab = A()
constructs A, then moves it to the variant. What you are thinking of isab.emplace<A>()
– Serous