Hi All,
I wanted to know in below code snippet what will be impact if m_singleObject is declared as a weak_ptr. Usaually we peform lock on weak_ptr and convert the same in to the shared pointer and then return the same to GetInstance() function.

static std::shared_ptr<singleType> shareObject = m_singleObject.lock

why can't we use direcltly shared_ptr for m_singleObject instead of by declaring weak_ptr and peforming the lock on the same as i did in below code snippet.

#include <iostream>
#include <memory>
using namespace std;
class a
{
public:
void fun(){cout<<"show";}

};

template<class singleType>
class Singleton
{
public:
    static std::shared_ptr<singleType> GetInstance();

private:
    //static std::weak_ptr<singleType> m_singleObject;
     static std::shared_ptr<singleType> m_singleObject;
    Singleton(const Singleton<singleType> &obj){};
    Singleton <singleType> & operator=(const Singleton<singleType> &obj) {}
    Singleton() {};
};
template<class singleType>
std::shared_ptr<singleType> Singleton<singleType>::GetInstance()
{
    static std::shared_ptr<singleType> shareObject = m_singleObject;
     //static std::shared_ptr<singleType> shareObject = m_singleObject.lock
    if (!shareObject)
    {
    shareObject = std::make_shared<singleType>();

    }

    return shareObject;
}


template <class singleType>

std::shared_ptr<singleType> Singleton <singleType> :: m_singleObject;


int main()
{

std::shared_ptr<a> obj =  Singleton <a>::GetInstance();


obj->fun();
return 1;
}

Did you intend that class a has no data and only 1 invariant method? Is that even valid?

Edited 8 Months Ago by Nutster

Hi,
Thanks for your response. Here class a canbe any class which you want to return only single instance. The idea is being that all clients of the singleton own a shared_ptr to it, and when all clients get destroyed, the singleton is also destroyed

This article has been dead for over six months. Start a new discussion instead.