🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

Verifying C++ Destructor Cleanup for regular pointers

Started by
10 comments, last by swiftcoder 7 years ago

Kinda in response to Shaarigan, I have to depart on that assessment of smart pointers. If I'm not mistaken the whole point of their existence is to acknowledge that things can, and do happen in a large enough code base (exceptions, most notably) that prevent the otherwise predictable flow control of the application reaching a method, or destructor that would otherwise perform the raw memory management.

If we are talking about std::unique_ptr (as I belive) then, not exclusively. Exception safety and such is a good side-effect, but really std::unique_ptr is a 1:1 replacement for 99% of the code where you used new/delete before. It has almost no downsides, default-member functions like ctors + forward declaration don't work well is the only I can think about. Upsides are drastically reduced chance of any accidential memory leak/double delete, reduced coding complexity (no explicit deletes in dtors etc... needed, especially valuable if you store stuff like std::vector<std::unique_ptr<>>!), and increased code readability by explicitely documenting the intended ownership in signature (func(Type* pRaw) vs func(std::unique_ptr<Type> pRaw)).

So really, you shouldn't be asking "why should I use std::unique_ptr", you should rather be asking "why should I still use raw new/delete"? :)

Advertisement

Upsides are drastically reduced chance of any accidential memory leak/double delete, reduced coding complexity (no explicit deletes in dtors etc... needed, especially valuable if you store stuff like std::vector<std::unique_ptr<>>!), and increased code readability by explicitely documenting the intended ownership in signature (func(Type* pRaw) vs func(std::unique_ptr<Type> pRaw)).

Plus it makes writing code that works in the presence of exceptions one hell of a lot easier...

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

This topic is closed to new replies.

Advertisement