我遇到了类似于 void pointer returned from function heap corruption 的问题
相似之处在于,当我离开使用 unique_ptr 的范围时,会收到“堆损坏”消息。
这里是代码:
void CMyClass::SomeMethod ()
{
std::unique_ptr<IMyInterface> spMyInterface;
spMyInterface.reset(new CMyInterfaceObject()); // CMyInterfaceObject is derived from IMyInterface
any_list.push_back(spMyInterface.get()); // any_list: std::list<IMyInterface*>
any_list.clear(); // only clears the pointers, but doesn't delete it
// when leaving the scope, unique_ptr deletes the allocated objects... -> heap corruption
}
知道为什么会这样吗?
最佳答案
std::unique_ptr 是一个智能指针,它通过指针保留对象的唯一所有权,并在 unique_ptr 超出范围时销毁该对象。
在你的例子中,你已经声明了 std::unique_ptr<IMyInterface> spMyInterface;
在 SomeMethod() 内部,因此一旦执行离开 SomeMethod() 的范围,您的对象就会被销毁。
关于c++ - 使用 unique_ptr 离开范围时堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10006767/