Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared_ptr from pointer

I have a class which can't be created on heap and it has private destructor.

But there is a function which returns a pointer to such constructed object. I want to make a shared pointer from it:

MyClass *GetMyClassPointer() {...}

boost::shared_ptr<MyClass> ptr;
ptr = boost::shared_ptr<MyClass>(GetMyClassPointer()); // [x]

error: ‘MyClass::~MyClass()’ is private

Any ways?

like image 619
Max Frai Avatar asked Jun 23 '26 03:06

Max Frai


1 Answers

Yes.

It sounds like the instance is being dynamically allocated by a function which has access to the private constructor (either member or friend). Then there should be a public function for cleaning up the instance when you're done with it, which has access to the private destructor (even though you don't).

Use the shared_ptr constructor that accepts a custom deleter, and wire it up to the cleanup function the class provides (may need a wrapper function to get the signature to match).

like image 127
Ben Voigt Avatar answered Jun 25 '26 18:06

Ben Voigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!