Peter said:
I am not sure I understand what you mean here. I believe the smart
pointer does protect my resource, whether it is memory, an open
file, a socket handle or something else.
I still do not understand. What do you mean by "store away and
forget it"? If it is still accessible from the program, you can
not deallocate it.
I mean the kind of bug that, with a raw pointer, is a dangling pointer.
You stored the pointer somewhere, in an Observer, or an event registry,
or something else, and forgot it was there. For example,
1. User A connects to my application. I new up a User object for him
and put it in a shared_ptr, and store it in my connected_users
collection.
2. User A subscribes to an event. The shared_ptr is now stored in the
event_registry collection.
3. User A logs out. I drop the reference from connected_users.
4. Oops. I forgot to drop the reference from event_registry. I leak
memory.
5. User A logs in again. Repeat from Step 1. I also now have multiple
copies of the same User in the system, and some may have stale data.
Without shared_ptr, it is a dangling pointer in the event_registry.
With shared_ptr, it is a memory leak. If "memory leak" is not exactly
the correct term, I have also heard them called "loitering objects". In
any case, it is a bug, and shared_ptr won't fix it. Except in
temporaries and simple aggregates, we still have to manage an object's
lifecycle properly.
This is not a specifically a problem with memory. It relates to all
ressources used by a program.
All resources that live long-term on the heap. Usually that is memory,
but someone could always put a file or something on the heap if they
had a reason to.
A dangling pointer? Using a smart pointer, it should never be
dangling. It could be 0, but that is expected.
With a smart pointer, you do not need to care.
If you want a resource freed and it doesn't free, it's a bug. It might
be your fault, for wanting it freed when the app still needs it, or it
might be the app's fault for holding onto it when it shouldn't. But
somewhere, there is a bug.