从类成员返回智能指针的正确方法?

Lio*_*ing 0 c++ singleton smart-pointers c++11

我正在尝试在person类中编写单例模式,这使我能够为该类创建一个实例,并且我可以在我的程序中的任何位置使用它.

以下是班级:

// The declaration
class Person {
    static unique_ptr<Person> instance;
    Person() = default;
    Person(Person&) = delete;
    Person& operator=(const Person&) = delete;
    ~Person() = default;
public:
    static unique_ptr<Person> getInstance();
};

// The implementation   
unique_ptr<Person> instance = NULL;
unique_ptr<Person> Person::getInstance() {
    if (instance == NULL) {
        instance = unique_ptr<Person>(new Person());
    }
    return instance;
}
Run Code Online (Sandbox Code Playgroud)

但它给我这个错误的问题: Error C2280 'std::unique_ptr<Person,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function

不幸的是,我不明白这个问题,我不知道如何解决?

R S*_*ahu 5

复制构造函数std::unique_ptr被隐式删除,因为它具有显式定义的移动构造函数.

C++ 11 Standard,12.8复制和移动类对象:

7如果类定义未显式声明复制构造函数,则会式声明一个.如果类定义声明了移动构造函数或移动赋值运算符,则隐式声明的复制构造函数被定义为已删除; 否则,它被定义为默认([dcl.fct.def]).

您可以通过以下方式解决问题:

  1. 返回对a的引用Person.

    static Person& getInstance();
    
    
    Person& Person::getInstance()
    {
       static Person p;
       return p;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 回来了shared_ptr<Person>.

    static std::shared_ptr<Person> getInstance();
    
    
    std::shared_ptr<Person> Person::getInstance()
    {
       static std::shared_ptr<Person> p(new Person);
       return p;
    }
    
    Run Code Online (Sandbox Code Playgroud)

我推荐第一种解决方案,因为它更简单.

PS请注意,它们都不需要使用static成员变量instance.