c++ - 返回 unique_ptr 私有成员数据而不转移所有权
问题描述
语境
下面的错误似乎告诉我,我无法从此 get 函数返回我的unique_ptr
调用。m_head
我只想在unique_ptr
m_head
不转让所有权的情况下退还我的。
自从引入智能指针以来,我一直在完全避免使用原始指针,因为原始指针不是异常安全的,存在内存管理开销和我已经意识到的其他问题。也许在这样的情况下,我应该在小范围内简要使用它们?
在这方面,我认为我需要转移所有权,而不是我目前的方法。我应该得到由管理的对象unique_ptr
,创建一个新shared_ptr
的来管理对象,然后返回shared_ptr
,但需要一些确认。我认为可能是这种情况,因为std::unique_ptr文档说:
unique_ptr 对象唯一地拥有它们的指针:没有其他设施应该负责删除该对象,因此没有其他托管指针应该指向它的托管对象,因为一旦他们不得不这样做,unique_ptr 对象就会删除他们的托管对象而不考虑 是否其他指针是否仍指向同一个对象, 因此将指向该处的任何其他指针都保留为指向 无效位置。
错误
`function "std::unique_ptr<_Ty, _Dx>::unique_ptr(const std::unique_ptr<_Ty, _Dx> &)
[with _Ty=mrobsmart::LinkedList::Node, _Dx=std::default_delete<mrobsmart::LinkedList::Node>]"
(declared at line 2337 of "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\include\memory")
cannot be referenced -- it is a deleted function
代码
#include <memory>
class LinkedList
{
private:
std::unique_ptr<Node> m_head;
public:
LinkedList(int data) {
m_head = std::make_unique<Node>(data);
}
const std::unique_ptr<Node> get_head() { return m_head; }
};
解决方案
我只想返回我的 unique_ptr m_head 而不转移所有权。
那是不可能的。unique_ptr
是围绕每一步都转移其所有权的行为而设计的。
请注意,自从引入智能指针以来,我一直在完全避免使用原始指针,因为原始指针不是异常安全的,有内存管理开销和其他我知道的问题,但也许在某些情况下我应该使用它们简要地包含在一个小范围内?
原始指针并不邪恶。将它们用作纯引用/间接引用是一个完全有效的用例——不涉及所有权、内存管理或异常安全。
当然,也可以返回 C++ 引用。选择指针还是引用,取决于值是否可以为null,但归根结底也是代码风格的问题。
因此,其中任何一个(重要:const
-qualify 函数):
const Node* get_head() const { return m_head.get(); }
const Node& get_head() const { return *m_head; }
推荐阅读
- java - 不要坚持主题卡夫卡
- html - 防止特定子元素扩展其父元素
- pandas - 如何在 seaborn 中使用 FacetGrid 绘制具有相同样式的单独线的不同试验?
- java - 如何通过 JFileChooser 保存 xml 文件
- javascript - 删除自定义标记(Google Maps Directions API)
- android - 压缩 Maybe 和 Single 会导致不发出任何结果
- excel - 将 Excel 的 SUMPRODUCT 与 SEARCH 一起使用并忽略空白单元格
- javascript - 如何通过javascript获取图像的大小?
- javascript - 带有 uikit 的粘性图像
- android - 无法在我的应用程序中使用 barteksc PDF 查看器