开发者

How does this forces singleton?

开发者 https://www.devze.com 2023-04-09 04:37 出处:网络
In some code, I saw singleton template template<typename T> class Singleton { public: Singleton(T& instance)

In some code, I saw singleton template

template<typename T>
class Singleton
{
public:
    Singleton(T& instance)
    {
        assert(!sfpInstance || (sfpInstance==&instance));
        sfpInstance = &instance;
    }
    stat开发者_StackOverflow中文版ic T& getInstance()
    {
        assert(sfpInstance);
        return *sfpInstance;
    }
private:
    static T*   sfpInstance;
};

And classes used like this:

class MyClass : public Singleton<MyClass>
{
   protected:
      MyClass() : Singleton<MyClass>(*this) {}
}

I don't know how can this be used as singleton?

If it can be used, what is the proper way to use it.

EDIT: MyClass constructor is protected.


This code won't work at all since there is no publicly available constructor of MyClass and Singleton is no friend of MyClass.

Now, if the MyClass constructor /were/ public, each call of the MyClass constructor would check whether the global sfpInstance pointer already points somewhere object, and triggers the assertion if it does. Thereby, only a single instance of MyClass can be constructed during the program run. Note that this method is not really elegant since it does not track the destruction of the MyClass singleton instance.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号