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

时间:2018-05-12 04:20:20

标签: c++11 singleton copy-constructor assignment-operator

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

请在下面的代码中查看详细信息: -

#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;
}

我错过了什么或者我的理解是错误的。

请帮忙。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

始终是相同的对象。您正在使用指针来访问该单例!

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