I create a parent class to handle singleton pattern with smart pointer:
.h file:
template<class singleType>
class Singleton
{
public:
static std::shared_ptr<singleType> GetInstance();
private:
static std::weak_ptr<singleType> m_singleObject;
};
.cpp file:
template<class singleType>
std::shared_ptr<singleType> Singleton<singleType>::GetInstance()
{
auto shareObject = m_singleObject.Lock();
if (!shareObject)
{
shareObject.reset(new singleType);
m_singleObject = shareObject;
}
return shareObject;
}
Not sure it is the right way to use smart pointer? Any idea?
Many Thanks
The pros and cons of this implementation are already discussed. But there are a bunch of bugs:
1) As this is a template you have to move your implementation into the header or the linker cannot find it.
2) The .lock()
function of the weak_ptr is not in capitals.
3) Don't forget to instantiate
template<class singleType>
std::weak_ptr<singleType> Singleton<singleType>::m_singleObject;
4) Better use shareObject = std::make_shared<singleType>(singleType());
instead of the new
: http://herbsutter.com/gotw/_103/
5) As Konrad mentioned: it's not thread-safe.