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...
'std :: unique_ptr '会起作用。 'shared_ptr'似乎没有你需要的语义。 –
juanchopanza
问题是你为什么要调用'factory()'而不从第一个地方获得返回值?我不会完全依靠科技来避免无意义的事情。 – billz
@juanchopanza - 你说得对,但遗憾的是我没有C++ 0x。 – Roddy