6

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.

Community
  • 1
  • 1
Shadasviar
  • 466
  • 5
  • 15

2 Answers2

18

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.

Barry
  • 286,269
  • 29
  • 621
  • 977
6

get_instance returns a reference to your singleton, which you then store in a local Settings_manager variable, which needs to make a copy. set should be a reference variable:

Settings_manager &set = Settings_manager::get_instance();
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56