I want to create a singleton class such that when all pointers to the class go away the destructor is called.
#include <memory>
#include <iostream>
class MyClass {
public:
uint8_t str[50]; //some random data
MyClass() {LOG("constructor Called"); }
~MyClass() {LOG("destructor Called");}
static std::shared_ptr<MyClass> &Get();
private:
static std::shared_ptr<MyClass> instance;
};
std::shared_ptr<MyClass> MyClass::instance=NULL;
std::shared_ptr<MyClass> &MyClass::Get()
{
if (instance == NULL)
{
instance= std::shared_ptr<MyClass>(new MyClass());
return instance;
}
return instance;
}
int main()
{
std::shared_ptr<MyClass> &p1 =MyClass::Get();
printf("We have %" PRIu32, p1.use_count());
if (1)
{
std::shared_ptr<MyClass> &p2 =MyClass::Get();//this should not
// create a new class
printf("We have %" PRIu32, p1.use_count()); //this should be two...
printf("We have %" PRIu32, p2.use_count()); //this should be two...
//when p1 goes out of scope here it should not call destructor
}
printf("We have %" PRIu32, p1.use_count());
//now destructor should be called
return 0;
}
The above code does not work as the static instance is a smart pointer and never goes out of scope, hence the destructor is never called.
What I would like to do is when the static instance is first created to return this instance of a smart pointer and then every call there after return a copy of this smart pointer.
A std::weak_ptr is what you're looking for.
By changing the instance to be a weak_ptr, it does not count as an owner to the shared pointer; meaning that once all other references have been released the object is destroyed. That said, it does make your "Get" function a little more complex, in that you must attempt to get a shared_ptr from the weak ptr, then on success return it, or on failure create a new one, re-assign instance to that ptr and return.
You can find more here
As a separate note, the destructor of your static member will be called, just not before main returns. Most people accept this feature of a static since once main returns they don't really care what happens as long as the application doesn't crash (although statics using other statics tends to result in exactly that)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With