mardi 27 octobre 2015

Singleton class implementation using shared_ptr

#include <iostream>
#include <memory>

using namespace std;

class Demo {
    static shared_ptr<Demo> d;
    Demo(){}
public:    
    static shared_ptr<Demo> getInstance(){
        if(!d)
        d.reset(new Demo);
        return d;
    }
    ~Demo(){
        cout << "Object Destroyed " << endl;
    }

};

//    shared_ptr<Demo> Demo::d(new Demo); // private ctor is accepted 

shared_ptr<Demo> Demo::d;

int main()
{
    shared_ptr<Demo> d(Demo::getInstance());
    cout << d.use_count() << endl;

   return 0;
}

  1. is this the correct way to implement the singleton class using shared_ptr
  2. please see above commented line to initialize the static shared_ptr how come we can create an object here to initialize shared_ptr with a private construct

Aucun commentaire:

Enregistrer un commentaire