繁体   English   中英

为什么不构造内部类? C ++

[英]why the internal class is't constructed? C++

这是我的源代码。

#include <iostream>
using namespace std;

class MySingleton;

template<class T>
class CSingleton
{
public:
    CSingleton()
    {
        cout << "constructor" << endl;
    }

    static T* GetInstance()
    {
        return m_Instance;
    }

private:
    static T* m_Instance;

    // This is important
    class CGarbageCollection
    {
    public:
        CGarbageCollection()
        {
            cout << "CGarbageCollection init\r\n";
        }

        ~CGarbageCollection()
        {
            // We can destory all the resouce here, eg:db connector, file handle and so on
            if (m_Instance != NULL)
            {
                cout << "Here is the test\r\n";
                delete m_Instance;
                m_Instance = NULL;
            }
        }
    };

    static CGarbageCollection gc;
};

template<class T>
typename CSingleton<T>::CGarbageCollection CSingleton<T>::gc;

template<class T>
T* CSingleton<T>::m_Instance = new T();

class MySingleton : public CSingleton<MySingleton>
{
public:
    MySingleton(){}
    ~MySingleton(){}
};

int main()
{
    MySingleton *pMySingleton = MySingleton::GetInstance();

    return 0;
}

当我构建项目时,内部类CGarbageCollection是否未构建? 为什么? 因为这与模板一起使用? 当我删除模板时,就可以了; 但现在,我无法收到消息。

因此,OP的问题是,为什么在模板情况下不实例化gc ,因为如果它不是模板,则会按照OP的期望进行实例化。 原因在“静态数据成员的实例化点”和此问题的答案C ++静态成员初始化(内部模板有趣)中得到了解释

长话短说,您需要在代码中usereference gc进行实例化。 例如,

static T* GetInstance()
{
    gc;
    return m_Instance;
}

将打印出预期的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM