我最近被意外调用了一个RemoveItem
函数,该函数返回了一个我应该拥有(但没有)拥有的指针,而不是调用DeleteItem
返回 void 的方法。
为了避免这种泄漏,从调用者应该获得返回对象所有权的函数返回的正确指针类型是什么?
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...