I found this code online for the singleton design pattern:
class Foo
{
public:
static Foo& getInstance()
{
static Foo instance;
return instance;
}
private:
Foo() {};
Foo(Foo const&);
Foo& operator=(Foo const&);
}
I don't understand why the constructor Foo(Foo const&);
and the Foo& operator=(Foo const&);
are both needed. Can someone explain to me please?
Wouldn't you want the following code to fail?
int main() {
// Utilizes the copy constructor
Foo x = Foo::getInstance();
Foo y = Foo::getInstance();
// Utilizes the operator=
x = Foo::getInstance();
}
Note that we've created 3 new instances of Foo
by the end of that code.
The copy constructor and assignment operator are declared in private section and not defined, which means that in fact no one can use them, so no copies of Foo
can be created.
Note that in C++11 this can be achieved in more straightforward way:
// this can be even in public section
Foo(Foo const&) = delete;
Foo& operator=(Foo const&) = delete;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With