错误 "Attempting to reference a deleted function" - 传回 unique_ptr 的值时



test.h

#include <memory>
#include <string>
using namespace std;
class A
{
public:
    A GetTitle();
private:
    unique_ptr<A> title;
};

test.cpp

#include <memory>
#include "Test.h"
A A::GetTitle()
{
    return *this->title.get();
} // Error here
int main()
{
}

我会收到以下错误:

c2280:'std :: unique_ptr> :: unique_ptr std :: unique_ptr&lt; _ty,std :: default_delete&lt; _ty>>&amp;)':试图尝试 引用已删除的函数

我在这里做错了什么?这取决于this->keyServer的所有权吗?我如何仅将值传递回去,以便我根本不允许该函数的用户在不使用setter的情况下修改类内的值?

A由于存在unique_ptr数据成员而无法复制。GetTitle()成员函数试图制作A的副本,因为它返回A,导致(误导)错误。

如果您想获得A的副本,则需要提供复制构造函数定义。


总的来说,您的示例很奇怪。如果A是一个独特的资源,您是否应该在该成员功能中制作它的副本?如果A::title实际上包含从A派生的类指针的指针怎么办?然后复制操作将无法按预期工作。

最新更新