c++ - 使用 unique_ptr 离开范围时堆损坏

标签 c++ scope c++11 unique-ptr

我遇到了类似于 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() 的范围,您的对象就会被销毁。

看看unique_ptr

关于c++ - 使用 unique_ptr 离开范围时堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10006767/

相关文章:

c++ - 显示来自 api 返回数据的特定数据,C++ REST SDK a.k.a Casablanka

php - 在单独的 PHP 脚本中访问全局变量?

C++ 11和 boost 几何

c++11 - 如何使用 libclang 检测枚举和作用域枚举之间的区别?

c++ - 使用 WinAPI 绘制图像 : LoadBitmap works but LoadImage() won't?

c++ - 使用 GLFW 渲染和 WinAPI 处理消息

c++ - 修复 Arduino 和 C++ Mac OS X 之间的通信

c++ - 除了使用 'extern' 关键字 :n3290 draft 之外,是否还有其他可能证明这一点

javascript - `function` 声明是函数范围的,但 `async function` 声明是 block 范围的?

c++ - 如果 `double` 或 `long double` 适合 `long long`,如何正确检查?