Unique_ptr析构函数说对象从未被分配 [英] Unique_ptr destructor saying object has never been allocated
问题描述
我有一个拥有一个Model对象的主进程。这样做的目的是在执行任务和修改相同模型的各个对象之间共享一个模型。
I have a main process that owns a Model object. The purpose of this is to share a Model between various objects that performs tasks and modifies the same Model.
现在,我为此对象创建一个unique_ptr,并将对该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上调用析构函数时,会发生一些奇怪的事情。它显示:
The tasks all complete correctly, but something weird happens when it tries to call the destructor on the unique_ptr. It shows:
RAW:内存分配错误:0xd0ebdfb2b8上的对象从未分配
RAW: memory allocation bug: object at 0xd0ebdfb2b8 has never been allocated
问题: p>
Question:
- 为什么会出现此错误?
- is unique_ptr是解决此问题的正确方法吗? >
- Why is this error happening?
- Is unique_ptr the right way to tackle this problem?
感谢
推荐答案
1 。
1. Why is this error happening?
无法看到您的代码,无法回答为什么会发生这种情况。
Without seeing your code it is impossible to answer why this is happening.
2。 is unique_ptr是解决这个问题的正确方法?
2. Is unique_ptr the right way to tackle this problem?
根据Straustrup和Sutter的核心指南
According to Straustrup and Sutter's Core Guidlines
R.30:以智能指针作为参数,仅显式地表达生命期语义
原因:接受智能指针, code> widget 是错误的,如果该函数只需要
小部件
本身。
它应该能够接受任何widget
对象,而不只是那些其生命周期由特定类型的智能指针管理的对象。
不操作生命周期的函数应该使用原始指针或引用。
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 thewidget
itself. It should be able to accept anywidget
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
添加到函数,如果该函数可能需要更改其所有权 。否则,您应该将 raw指针或引用传递给 unique_ptr
正在管理的对象。
You should only be passing a std::unique_ptr
to a function if that function may need to alter its ownership. Otherwise you should pass the raw pointer or a reference to the object that the unique_ptr
is managing.
这篇关于Unique_ptr析构函数说对象从未被分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!