vendredi 4 mai 2018

The right way to return a smart pointer from a class member?

I am trying to write the singleton pattern in the person class which gives me the ability to create just one instance for that class and I can use it in any place in my program.

The following is the class:

// 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;
}

But the problem that it gives me this error: 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

Unfortunately, I don't understand that problem and I don't know how to solve?

Aucun commentaire:

Enregistrer un commentaire