gpt4 book ai didi

c++ - 从函数返回指针

转载 作者:行者123 更新时间:2023-11-28 07:20:34 25 4
gpt4 key购买 nike

我最近不小心调用了一个 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...

最佳答案

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

关于c++ - 从函数返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19537105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com