Unique_ptr 析构函数说对象从未被分配

Unique_ptr destructor saying object has never been allocated

我有一个拥有模型对象的主进程。这样做的目的是在执行任务和修改同一模型的各种对象之间共享一个模型。

现在,我为该对象创建了一个 unique_ptr 并将对该 unique_ptr 的引用传递给其他对象以执行某些任务。

所有任务都正确完成,但是当它试图调用 unique_ptr 上的析构函数时发生了一些奇怪的事情。它显示:

RAW:内存分配错误:从未分配 0xd0ebdfb2b8 处的对象

问题:

  1. 为什么会出现这个错误?
  2. unique_ptr 是解决这个问题的正确方法吗?

谢谢

我需要查看代码示例才能为您提供具体的解决方案或反馈。

然而,这一行:

Right now, I create a unique_ptr to this object and pass a reference to that unique_ptr to other objects to perform certain tasks.

我觉得很可疑。将引用传递给您的 unique_ptr (或其他拥有的数据结构)几乎总是不正确的。您应该赞成对底层对象的简单引用;也就是说,您应该将 std_unqiue_ptr<Model>& 的所有实例替换为 Model&.

当我读到它时:

Right now, I create a unique_ptr to this object and pass a reference to that unique_ptr to other objects to perform certain tasks.

我明白了

std::unique_ptr<type> u( new type() );
std::unique_ptr<type> w = u;

但是unique_ptr的原则是只处理一次。这会引发错误,因为 unique_ptr-wrapped 对象的复制构造函数被禁用。

但没有例子,很难回答:)

与此处的一些答案相反,通过 const 引用传递管理实体(shared_ptr、unique_ptr)并没有错。事实上,在某些情况下,通过引用传递可能是使用 unique_ptr 的唯一方法,并且首选使用 shared_ptr。示例:

void foo(const std::shared_ptr<obj_t>/*&*/ obj) { obj->func(); }

没有引用,就会有一个不必要的引用计数器increment/decrement,导致性能延迟。不,有人会争辩说没有必要在 foo() 中使用 shared_ptr 开始,我同意,但我见过的一些开发环境对 'no naked pointers in our code!' 非常严格,并且争论他们错了可能会让你失去工作。在这种情况下,通过引用传递是解决方案。

1. 为什么会出现这个错误?

如果没有看到您的代码,就不可能回答为什么会这样。

2。 unique_ptr是解决这个问题的正确方法吗?

根据 Straustrup 和 Sutter 的 Core Guidlines

R.30: Take smart pointers as parameters only to explicitly express lifetime semantics

Reason: Accepting a smart pointer to a widget is wrong if the function just needs the widget itself. It should be able to accept any widget object, not just ones whose lifetimes are managed by a particular kind of smart pointer. A function that does not manipulate lifetime should take raw pointers or references instead.

如果某个函数可能需要更改其 所有权 ,您应该只将 std::unique_ptr 传递给该函数。否则,您应该将 原始指针 引用 传递给 unique_ptr 正在管理的对象。