在C++中,如何初始化在Singleton模板中声明的私有类的静态成员?

teu*_*oui 3 c++ inheritance singleton templates

好吧,我应该简单地说我想创建一个我可以继承的基础Singleton类,以及我希望通过模板实现的方式.

为了避免内存泄漏,我不直接使用指向实例的指针,而是使用将处理删除指针的私有类.

这是我的实际代码(不工作):

template <typename T> class Singleton
{
private:
    class PointerInstance
    {
    private:
        T* instance;
    public:
        PointerInstance() : instance(0) {}
        ~PointerInstance() { delete instance; } // no memory leak !
        T* Get()
        {
            if ( !instance ) {
                instance = new T();
            }
            return instance;
        }
    };
    static PointerInstance PInstance;
public:
    static T* pGetInstance(void)
    {
        return PInstance.pGet();
    };
protected:
    Singleton(void){};
    ~Singleton(void){};
};
Run Code Online (Sandbox Code Playgroud)

这是典型的派生类声明应该是这样的:

class Child : public Singleton<Child>
{
    friend class Singleton<Child>;
    Child();
    // etc...
};
Run Code Online (Sandbox Code Playgroud)

基本上缺少的是我作为Singleton的每个T类的PInstance实例.

我的问题是:有没有办法一劳永逸地在包含上面代码的Singleton.h中使用一些通用代码行,或者除了为每个代码添加一些特定的代码行之外别无选择衍生类?

(Bonus:有没有更好的方法在C++中使用Singleton类?)

Joh*_*itb 5

template <typename T> 
typename Singleton<T>::PointerInstance Singleton<T>::PInstance;
Run Code Online (Sandbox Code Playgroud)

在类之外的标题中.请注意,无论您在PInstance默认构造函数中编写什么,如果您从未调用pGetInstance或从未以PInstance非另一种方式从非模板代码引用,则代码将永远不会执行.但那应该没问题.