0

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...
11
  • 2
    An std::unique_ptr<Base> would work. A shared_ptr doesn't seem to have the semantics you require. Commented Oct 23, 2013 at 8:52
  • the problem is why would you call factory() without getting hold of the return value from first place? I won't totally rely on tech to avoid nonsense things. Commented Oct 23, 2013 at 8:56
  • @juanchopanza - You're right, but sadly I don't have C++0x. Commented Oct 23, 2013 at 8:58
  • 1
    Actually, std::auto_ptr<Base> might be suitable in this case. Commented Oct 23, 2013 at 9:00
  • 2
    @Roddy Then use std::auto_ptr. A factory function should never return a shared_ptr (Boost or standard), because this forces the client to use shared_ptr, even if he doesn't want to share. Commented Oct 23, 2013 at 11:26

1 Answer 1

1

The obvious solution is to have only one function, which returns and std::auto_ptr (since you say you don't have C++11). This will cause the object to be deleted unless the caller does something with it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.