C++ Outside the box smart pointers

Started by
11 comments, last by wintertime 10 years, 5 months ago

Can you elaborate on this? 'placement new' ? How would the double destruction occur given the check in the destructor checking the ref count? Is that generally the blanket answer for anytime someone is calling a destructor manually?



Explicitly calling a destructor is only safe in very select circumstances. If you aren't familiar with placement new, go look it up, descriptions and examples are abundant on the web.

Your code as posted has a bug. If I delete Object enough times to cause the wrapped object to hit a refcount of 0, and then let the Object go out of scope, it will double-delete the wrapped object. Your destructor is not safe if refcount == 0 at the time that it is called.


Furthermore, calling free() on memory allocated with new() is also bad juju. The correct thing to do is replace your manual destructor call and the call to free() with a delete call, in which case your bug might jump out at you a bit easier.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Advertisement
I'm very confused about what problem this design is supposed to solve. Can you explain that better?

It reads a bit like: "I dont like templates, therefore I create an unsafe half-smart pointer myself."

Somewhere you need the exact type of the object and only a template provides a good way to do this. You could get away with making a smart pointer handling void* and then casting yourself on use, but the automatic deallocation needs the type if its not pod class allocated in a compatible way (for example with new unsigned char[size] and later cast back and use operator delete[]). That means such a smart-pointer will not be useful for many classes and unsafe from the unchecked outside casting on use.

You would also need a #define make_pointer that calls the explicit constructor with a sizeof and then does a memset or placement new as appropriate.

And copy constructor, operator=, destructor for handling the refcount.

This topic is closed to new replies.

Advertisement