by wfunction · 12y ago · 0 comments
You're exactly right. But there are multiple complications:
- unique_ptr and shared_ptr are only available in C++11 onwards, we're still to migrate to a new compiler
- auto_ptr is a joke [1]
- I've got to live with `delete` in our gargantuan codebase at work
- I could (and should) use boost's smart pointers, and indeed I do when possible. But I admit I sometimes even forget to use those and end up with naked pointers instead.
And if you really can't, and you need a container that automatically frees its contents when destroyed, just stick it in a STL vector.
std::unique_ptr (or its predecessor, boost:scoped_ptr if you don't have access to C++11) should be used all over the place. There are many reasons why you may not want by-value containment of objects, and std::unique_ptr gives you object-lifetime ownership of pointers.
But aesthetically, I've learned to distrust any code that likes to throw objects around the design by pointer. It's untidy, and leads to needless abstraction and poor coupling. The time you spend trying to fit your objects into by-value composition is time you save later not having to untangle your knots of pointers.
I'm interested in reading them actually, would you mind listing them?
You don't always have control over the code you are writing, an example that comes to my mind quickly is ffmpeg.
Smart pointers are not a panacea.