
Sohail Somani wrote:
I was recently torn between doing this or thinking whether I'm doing it wrong. I'm still not sure whether using shared pointers everywhere with null deleters for stack allocated objects is The Right Thing. It kind of defeats the purpose of shared_ptr which is to ensure that the lifetime of the pointer is guaranteed for you. With null deleters, maintenance programmers may do the wrong thing (stuff something in an event queue deep down, for example.)
If anyone has any opinion (for or against) please shout!
I would say that this is a bad idea. It seems like there is an implicit contract when using shared_ptrs that the object won't be destroyed as long as anyone has a copy of that shared_ptr. (One way to advertise that copies of the smart pointer might not preserve the object could be to pass a weak_ptr instead of a shared_ptr. Unfortunately, the lock method of the weak_ptr could still cause problems because it returns a shared_ptr, and you could still end up with a stale pointer.) Overall, it seems like using a shared_ptr for stack objects is misleading, and as a result, may eventually lead to difficult to trace bugs. Unless allocating and deallocating the object is a bottleneck in your code, the potential costs outweigh the benefits. David