C++ – Smart Pointers inside class vs Normal Pointers with Destructor

cclassmemorypointerssmart-pointer

Regarding pointers which are members of classes. Should they be of a smart pointer type or is it enough to simply deal with them in the destructor of the class they are contained in?

Best Answer

No, it's not enough to deal with the raw pointer in the destructor. You also have to deal with it in the copy constructor and assignment operator functions. It's usually not enough to simply copy the pointer (which the compiler will happily do for you); you probably really want to make a copy of the resource it points to. And you have to remember to gracefully handle self-assignment without leaking the resource. Maybe you don't want to support copying at all, so you have to remember to explicitly disable those functions. Maybe you want to give out handles to that resource, so you have to keep track of when it's safe to be freed. What if an exception is thrown in the middle of your constructor? What if you aren't the one throwing it? Maybe there's another edge case I haven't thought of.

(Note: I've debugged more than enough of this kind of code that gets it wrong, hence my somewhat harsh tone.)

If you want to get it right on the first try, then yes, you should go with a smart pointer type such as boost::scoped_ptr or std::tr1::shared_ptr.