dimanche 13 janvier 2019

Is this really a achieve the single instantiation of a Singleton class [duplicate]

This question already has an answer here:

Following Singleton Design Pattern c++ code is confusing for me

#include <iostream>

using namespace std;

class Singleton
{
    int data;
    Singleton(){}
    public:

    void setData(int n)
    { data = n;}

    int getData(){
        return data;
    }

    static Singleton& get()
    {
        static Singleton db;
        return db;
    }
};
int main()
{
    Singleton d = Singleton::get();
    d.setData(200);
    cout<<"D:"<<d.getData()<<endl;  // Output is D: 200

    Singleton d1 = Singleton::get();
    d1.setData(300);
    cout<<"D1:"<<d1.getData()<<endl; // Output is D1: 300
    cout<<"D:"<<d.getData()<<endl;   // Output is D: 200. It should have been 300
   return 0;
}

In above example i can create as many objects of singleton class and have different values of private member "data". So my question how the singleton is achieved above

Aucun commentaire:

Enregistrer un commentaire