I've used boost::variant for some time and now I'm trying to figure out how it internally works. I wrote a simple test and I can't understand the results. Here it is (simplified)
struct my_type
{
my_type(){ cout << (size_t)this << " construction"; }
~my_type(){ cout << (size_t)this << " destruction"; }
};
int main()
{
variant<int, my_type> x;
x = my_type();
}
The output of such program is
140736940365327 construction <-- A
140736940365236 destruction <-- ?
140736940365327 destruction <-- A
140736940365332 destruction <-- ?
Why the hell the destructor is not called as many times as the constructor ? As destructors are called over the heap, I'm aware that this may not segfault, but it seems to me that this behaviour is dangerous. Am I missing something ? Is this related to the "backup" mechanism of boost::variant ?