Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of deleted copy constructor in the singleton

I've implemented the singleton pattern like this, there is my code:

header file:

class Settings_manager{
public:
    static Settings_manager& get_instance();

    void operator=(Settings_manager const&) =delete;
    Settings_manager(Settings_manager const&) =delete;
...

private:
    Settings_manager();
};

implementation:

Settings_manager& Settings_manager::get_instance()
{
    static Settings_manager instance;
    return instance;
}

Settings_manager::Settings_manager()
{
    read_file();
}

When I try use get_instance function in main like this:

Settings_manager set = Settings_manager::get_instance();

or Settings_manager set = std::move(Settings_manager::get_instance());

I get

error: use of deleted function 'Settings_manager::Settings_manager(const Settings_manager&)'
 Settings_manager set = Settings_manager::get_instance();

Can somebody tell, what's wrong and explain it? Thanks.

like image 918
Shadasviar Avatar asked Oct 08 '16 16:10

Shadasviar


People also ask

Why do we delete the copy constructor?

Copy constructor (and assignment) should be defined when ever the implicitly generated one violates any class invariant. It should be defined as deleted when it cannot be written in a way that wouldn't have undesirable or surprising behaviour.

How do I delete an object in Singleton?

And deletion of singleton class object would be allow only when the count is zero. To design C++ delete singleton instance, first, we need to make the singleton class destructor private, so, it can not be accessed from outside of the class. Hence, user cannot delete the singleton instance using the keyword “delete”.

Why is the constructor and copy constructor private in the singleton class?

The constructor, copy constructor and assignment operator are all private to ensure that the programmer using the singleton class can only create a single instance of the class using only the Instance() function.

Does Singleton need destructor?

Because all the member functions of this class are static and the class has no instance variables, it is not required that the class be instantiated. The member functions can be used without an instance of the class. Thus there is no need to implement constructors or a destructor for this class.


1 Answers

Consider what you're trying to do here:

Settings_manager set = Settings_manager::get_instance();

You have your singleton, get_instance(), and you're trying to copy it? That would kind of defeat the purpose of singleton if you could just... create two of them right?

You want to take a reference:

Settings_manager& set = Settings_manager::get_instance();

This way, set is the singleton instance. Not a copy of it.

like image 93
Barry Avatar answered Oct 12 '22 10:10

Barry