Jump to content
  • Advertisement
Sign in to follow this  
rpiller

C++ Outside the box smart pointers

This topic is 2102 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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. Edited by ApochPiQ

Share this post


Link to post
Share on other sites
Advertisement

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.

Edited by wintertime

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!