I got caught out recently by accidentally calling a RemoveItem function that returned a pointer that I should have taken ownership of (but didn't), instead of calling a DeleteItem method which returned void.
To avoid this kind of leak, what's the right kind of pointer to return from a function where the caller is expected to take ownership of the returned object?
Base * factory()
{
if (condition)
return new DerivedA;
else
return new DerivedB;
}
...
boost::scoped_ptr<Base> b(factory()); // no leak here
factory(); // but this leaks, obviously
Should factory() return a shared pointer to prevent the leak?
The factory example should be familiar, but here's the kind of thing that caused me a problem:-
void DeleteItem(ItemName); // delete named item from structure.
Item* RemoveItem(ItemName); // removes named item from the structure, and returns it.
//Caller can then re-insert it elsewhere.
RemoveItem("Fred"); // whoops! Should have called DeleteItem.
// Apart from the leak, everything appears OK...
std::unique_ptr<Base>would work. Ashared_ptrdoesn't seem to have the semantics you require.factory()without getting hold of the return value from first place? I won't totally rely on tech to avoid nonsense things.std::auto_ptr<Base>might be suitable in this case.std::auto_ptr. A factory function should never return ashared_ptr(Boost or standard), because this forces the client to useshared_ptr, even if he doesn't want to share.