I have been recently asked about singleton design pattern in c++. I didn't know exactly what it does or when it is required, so I tried googling it. I found a lot of answers primarily on stackoverlow but I had a hard time understanding the code mentioned in these questions and answers. I know following property that a singleton should satisfy, correct me if I am wrong.
It is used when we need to make one and only one instance of a class.
This raises following question in my mind
Does this mean that it can be created only once or does this mean that it can be
created many times but at a time only one copy can exist?
Now coming to the implementation. copied from here
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {}; // Constructor? (the {} brackets) are needed here.
// Don't forget to declare these two. You want to make sure they
// are inaccessible otherwise you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
};
Please explain:
- Why do we have to make getinstace() function static?
- Why do we need S(S const&); constructor?
- What does void operator=(S const&); do?
- Why don't we implemented last two function?
- Why do we need the guaranteed destruction of this instance(as mentioned in the code)?