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