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

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

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

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

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

是我遗漏了什么还是我的理解有误

请帮忙解决这个问题。 提前致谢。

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

这就像有 3 个鸡蛋盒,但只有一个鸡蛋 "over time" 放在不同的盒子里。这种比较并不完美,但希望足够接近。