Singleton implementation - why is a copy constructor needed?

回眸只為那壹抹淺笑 提交于 2020-08-04 08:56:37

问题


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?


回答1:


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.




回答2:


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;



回答3:


To prevent accidentally assigning the singleton.

With private copy constructor the following code will NOT compile:

Foo foo = Foo::getInstance(); // error: ‘Foo::Foo(const Foo&)’ is private

With private no argument constructor the following code will NOT compile:

Foo foo2; // error: ‘Foo::Foo()’ is private

You use this gymnastics to ensure that people who use your singleton will use it the way it was intended, through the getInstance() static function.



来源:https://stackoverflow.com/questions/26266242/singleton-implementation-why-is-a-copy-constructor-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!