Quote:Original post by Sneftel
It's perfectly fine to have two shared_ptrs to the same object. That's why they call them SHARED_ptr.
Isn't that only when the all shared_ptrs except the first one are constructed/assigned from the first shared_ptr, rather than being constructed from the raw pointer itself? In his code, it appears as though he's resetting StashedObject to reference obj, and is then returning obj, which should cause the creation of another shared_ptr. (Except I'm expecting that part to fail, if I remember correctly, because a shared_ptr must be constructed explicitly, right?) So even with an explicit constructor on the return:
shared_ptr<Object> LoadObject(string name){ Object *obj = somehowLoadObject(); StashedObject.reset(obj); return shared_ptr<Object>(obj);}
Wouldn't that create two independent sets of shared_ptrs that point to the same thing, each thinking they own that block of memory? And thus get the double-delete issue that xstreme2000 was worried about? I would think that this would be the proper way to do it:
shared_ptr<Object> LoadObject(string name){ Object *obj = somehowLoadObject(); StashedObject.reset(obj); return StashedObject;}
By creating a copy of StashedObject, you still only have one set of shared_ptrs. StashedObject is the only one that is ever constructed/reset from the raw pointer.
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas only, and not for things themselves." - John Locke