【问题标题】:why the internal class is't constructed? C++为什么没有构造内部类? C++
【发布时间】:2014-08-14 15:58:16
【问题描述】:

这是我的源代码。

#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没有构建?为什么?因为这是与模板一起使用的?当我删除模板时,没关系;但现在,我无法收到消息。

【问题讨论】:

  • 如果你坚持使用单例模式,should be considered harmful,你至少应该知道/使用Meyers singleton
  • @NeilKirk:这不是线程安全的,应该避免。
  • @NeilKirk 更好的是,将 unique_ptr 设为函数的 static 局部变量。使用 C++11 线程安全静态,您无需付出额外的努力即可获得线程安全。
  • @Angew:为什么需要免费分配商店?
  • @RobertAllanHenniganLeahy 当然你不知道。我只是在评论“静态unique_ptr”部分。

标签: c++ templates static internal


【解决方案1】:

所以 OP 的问题是,为什么 gc 在模板情况下没有被实例化,因为如果它不是模板,它会按照 OP 的预期被实例化。原因在Point of Instantiation of Static Data Members 和这个问题的答案C++ Static member initalization (template fun inside) 中进行了解释。

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

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

将打印出预期的结果。

【讨论】:

    猜你喜欢
    • 2011-10-19
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-02
    • 2012-02-08
    相关资源
    最近更新 更多