使用unique_ptr离开范围时堆损坏

Rob*_*ger 5 c++ scope unique-ptr c++11

我遇到类似于函数堆损坏返回的void指针的问题

相似之处在于,当离开使用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
}
Run Code Online (Sandbox Code Playgroud)

知道为什么会这样吗?

fla*_*ari 3

std::unique_ptr 是一个智能指针,它通过指针保留对象的唯一所有权,并在 unique_ptr 超出范围时销毁该对象。

在您的情况下,您已std::unique_ptr<IMyInterface> spMyInterface;在 SomeMethod() 内部声明,因此一旦执行离开 SomeMethod() 的范围,您的对象就会被销毁。

看一下unique_ptr

  • 好的,但是这如何解释堆损坏呢? (6认同)