On January 29, 2016 5:25:49 AM EST, Andrey Semashev
On 2016-01-29 12:40, Rob Stewart wrote:
On January 29, 2016 2:48:56 AM EST, Emil Dotchevski
wrote:
The point of shared_ptr is to be able to reason that as long as you hold on to a shared_ptr (which you might get by copying another shared_ptr or by locking a weak_ptr), the object will not expire, but you don't hold on to it longer than you need to. This reasoning is perfectly valid within the scope of do_something.
If do_something() saves a copy of the shared pointer in a container, for example, later references will refer to a non-existent object. There's nothing you can do about it short of using assertions or another runtime check with a call to std::terminate() or similar. That's hardly ideal.
I think what Emil describes is a special case of a 'dangling_ptr' idiom, if I may call it that way. The point is that there are cases when object lifetime is controlled by a third party (e.g. the stack state, a foreign library, etc.) and you need a safe way to know when the object has been deleted. So you create a shared_ptr with a null_deleter pointing to that object and save it in that object (or another storage associated with that object). You keep only weak_ptrs to that object in all other places in the code. When you need to use the object you have to lock a weak_ptr and thus check if the object is still alive.
I understand that full well. The example that Emil presented can easily lead to having shared_ptrs that refer to release stack memory. ___ Rob (Sent from my portable computation engine)