Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it right way to create sinlgeton class by weak_ptr

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

like image 276
Mark Guo Avatar asked Apr 22 '13 05:04

Mark Guo


1 Answers

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.

like image 193
Gerrit Avatar answered Sep 19 '22 12:09

Gerrit