为什么单例设计模式允许复制对象,甚至复制构造函数和赋值运算符都是私有的?

why singleton design pattern allowing copy of object even copy constructor and assignment operator are private?

提问人:HumbleSwagger 提问时间:5/12/2018 最后编辑:Venki WARHumbleSwagger 更新时间:5/12/2018 访问量:277

问:

我创建了下面的单例类,并将复制构造函数和赋值运算符定义为私有的。当我调用复制构造函数或赋值运算符时,它不会调用复制构造函数和赋值运算符(可能是由于静态对象创建)。所以我的问题是,为什么单例设计模式允许创建对象的副本或分配新对象(这违反了创建类的单个实例化的基本要求)从先前创建的对象中,即使它们在类中被声明为私有?

有关详细信息,请考虑以下代码:-

#include <iostream>
#include "conio.h"
class singleton
{
static singleton *s;
          int i;

            singleton()
            {
            };          
            singleton(int x):i(x)
            { cout<<"\n Calling one argument constructor";
            };

            singleton(const singleton&)
            {
                cout<<"\n Private copy constructor";
            }

            singleton &operator=(singleton&)
            {
                cout<<"\n Private Assignment Operator";
            }

    public:
         static singleton *getInstance()
         {
            if(!s)
            {
                cout<<"\n New Object Created\n ";
                s=new singleton();
                return s;   
            }
             else
                {
                    cout<<"\n Using Old Object \n ";
                    return s;
                }

         }  
        int getValue()
        {
            cout<<"i = "<<i<<"\n";
            return i;
        }
        int setValue(int n)
        {
            i=n;
        }
};

singleton* singleton::s=0;

int main()
{
    // Creating first object

    singleton *s1=  singleton::getInstance();
    s1->getValue();

    singleton *s4=s1;    // Calling copy constructor-not invoking copy ctor
    singleton *s5;
    s5=s1;              // calling assignment operator-not invoking assign ope

    //Creating second object
    singleton *s2=singleton::getInstance();
    s2->setValue(32);
    s2->getValue();

    //Creating third object
    singleton *s3=singleton::getInstance();
    s3->setValue(42);
    s3->getValue();

    getch();
    return 0;
}

是我遗漏了什么,还是我的理解错了。

请帮忙。 提前致谢。

C++11 单例 复制构造函数 赋值运算符

评论

0赞 tkausl 5/12/2018
您复制的是指针,而不是对象。
0赞 HumbleSwagger 5/12/2018
如果构造函数是私有的,它甚至不允许单个对象
0赞 tkausl 5/12/2018
事实并非如此,类本身(及其朋友)被允许访问私有方法和成员,而这正是您在 .getInstance
0赞 HumbleSwagger 5/12/2018
因此,它将允许指针复制,以便我可以创建指向同一对象的多个指针。我的理解正确吗?
0赞 GhostCat 9/21/2018
我很感激接受。欢迎到点赞级别;-)

答:

1赞 GhostCat 5/12/2018 #1

它始终是同一个对象。您正在使用指针在此处访问该单例!

这就像有 3 个鸡蛋盒,但只有一个鸡蛋,“随着时间的推移”放在不同的盒子里。这种比较并不完美,但希望足够接近。

评论

0赞 HumbleSwagger 5/12/2018
你的意思是单例允许多个指针指向一个类的相同(单个)对象?。但根据我的理解,单例只允许类的单个实例化(单指针)。
0赞 GhostCat 5/12/2018
指针不是实例化!指针指向实例。一个鸡蛋,三盒!但只有一个鸡蛋!
0赞 HumbleSwagger 5/12/2018
同意。在 getInstance() 中,我只创建了一个对象,多个指针都引用了该对象。我现在明白了构造函数需要是私有的,这样它就不允许在驱动程序(主)代码中创建对象。但是,为什么我们需要赋值运算符私有呢?
0赞 Konstantin T. 5/12/2018
我们真的不需要它。但通常它是私有的,因为无论如何我们不需要它们公开。还要记住,它是C++,所以可以编写一些愚蠢的代码:.singleton * sgl_ptr = static_cast<singleton *>(malloc(sizeof(singleton ))); *sgl_ptr = sgl;