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

Error "Attempting to reference a deleted function" - when passing back value of 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(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function

我在这里做错了什么?这取决于 this->keyServer 的所有权吗?我如何只传回值,这样我就根本不允许函数的用户在不使用 setter 的情况下修改 class 中的值?

由于 unique_ptr 数据成员的存在,

A 不可复制。 GetTitle() 成员函数试图复制 A,因为它 returns 按值 A,导致(误导性)错误。

如果您希望能够复制 A,您需要提供复制构造函数定义。


总的来说,你的例子很奇怪。如果 A 是唯一资源,您是否应该在该成员函数中复制它?如果 A::title 实际上包含一个指向从 A 派生的 class 的指针怎么办?那么复制操作将不会按预期工作。