Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton implementation - why is a copy constructor needed?

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?

like image 933
Mertcan Ekiz Avatar asked Oct 08 '14 20:10

Mertcan Ekiz


2 Answers

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.

like image 70
Bill Lynch Avatar answered Nov 26 '22 10:11

Bill Lynch


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;
like image 26
Anton Savin Avatar answered Nov 26 '22 10:11

Anton Savin