Reputation: 121
I know this might sound strange but I would like to reinitiate a singleton to set all its variables back to default. I have the following singleton class:
class Singleton {
public:
static Singleton &getInstance(){
static Singleton instance;
return instance;
}
Singleton(const Singleton &) = delete;
Singleton(Singleton &&) = delete;
Singleton &operator=(const Singleton &) = delete;
Singleton &operator=(Singleton &&) = delete;
static void clearSingleton(){
//Recreate instance object??
}
int a = 0;
int b = 0;
int c = 0;
//etc...
}
My program does a lot of changing of the variables like:
Singleton::getInstance().a = 5;
Singleton::getInstance().b = 8;
//etc...
After a while I need all variables to be reset. I could of coarse add a reset function to the singleton that would set all the variables but since they are so many, and it is easy to forget to add new variables to the reset function, I would just want to drop the singleton and recreate it. In that case all variables would be reset automatically. How can I do this?
Upvotes: 1
Views: 727
Reputation: 60238
If you just default the move-assignment operator, but make it private:
class Singleton {
Singleton &operator=(Singleton &&) = default;
public:
// ...
};
you can write:
static void clearSingleton() {
getInstance() = Singleton{};
}
Here's a demo.
You can do this for all the special member functions, so you might as well, to be consistent.
Upvotes: 3