2013-10-23 172 views
0

我最近意外地调用了一个函数RemoveItem,它返回了一个我应该拥有(但没有)的指针,而不是调用返回void的DeleteItem方法。从函数返回指针

为了避免这种泄漏,从调用方期望获得返回对象所有权的函数返回的指针的正确类型是什么?

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 

应该factory()返回一个共享指针,以防止泄漏?


工厂的例子应该是熟悉的,但在这里是引起了我一个问题,这样的事情: -

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... 
+2

'std :: unique_ptr '会起作用。 'shared_ptr'似乎没有你需要的语义。 – juanchopanza

+0

问题是你为什么要调用'factory()'而不从第一个地方获得返回值?我不会完全依靠科技来避免无意义的事情。 – billz

+0

@juanchopanza - 你说得对,但遗憾的是我没有C++ 0x。 – Roddy

回答

1

显而易见的解决方案是只有一个函数,返回 和std::auto_ptr(因为你说你没有C++ 11)。这个 将导致该对象被删除,除非调用者使用 。