Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have created below singleton class and defined copy constructor and assignment operator as a private. When I invoke copy constructor or assignment operator, it does not call copy constructor and assignment operator(Maybe due to statically object creation). So my question is why singleton design pattern allows creating copy of object or assigning new object(which violates basic requirement of creating single instantiation of a class) form previously created object even they are declared private in a class?

Consider below code for details:-

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

Am I missing something or my understanding is wrong.

Please help in this. Thanks in advance.

like image 692
HumbleSwagger Avatar asked Dec 01 '25 06:12

HumbleSwagger


1 Answers

It is always the same object. You are using pointers to access that singleton here!

It is like having 3 egg boxes, but only one egg, that "over time" placed in the different boxes. That comparison isn't perfect, but hopefully close enough.

like image 122
GhostCat Avatar answered Dec 05 '25 01:12

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!