I wrote the following code to see how a shared_ptr<void>
would behave when it is the last reference to a shared_ptr<Thing>
and is itself destroyed.
#include <iostream>
#include <string>
#include <memory>
using namespace std;
struct Thing{
~Thing(){
cout<<"Destroyed\n";
}
int data;
};
int main(){
{
shared_ptr<void> voidPtr;
{
shared_ptr<Thing> thingPtr = make_shared<Thing>();
voidPtr = thingPtr;
}
cout<<"thingPtr is dead\n";
}
cout<<"voidPtr is dead\n";
return 0;
}
Which outputs:
thingPtr is dead
Destroyed
voidPtr is dead
It behaves in a way I like, but it's totally unexpected and I'd like to understand what's going on here. The initial shared pointer no longer exists, it's just a shared_ptr<void>
in the end. So I would expect this shared pointer to act like it's holding a void*
and have no idea about Thing::~Thing()
, yet it calls it. This is by design, right? How is the void shared pointer accomplishing this?