3

新しい C++11 クラス内メンバー初期化子を使用して、コンパイル時にシングルトンを初期化できるかどうかを考えていました。これにより、アプリケーションの一部のマネージャー クラスの速度が向上する可能性があります。

class CSingleton
{
public:
    CSingleton(void) {}
    ~CSingleton(void) {}
    static const CSingleton* GetInstance(void)
    {
        return Instance;
    }

    bool Foo1(int x);
    bool Foo2(int y);
private:
    static constexpr CSingleton *Instance = new CSingleton();
}

問題は、これにより次のエラーが発生することです。

Line of Instance declaration:    error: invalid use of incomplete type 'class test::CSingleton'
First Line of class declaration: error: forward declaration of 'class test::CSingleton'

これまたは別のアプローチでコンパイル時にシングルトンを初期化する方法はありますか?

[MacOSX10.7 (および Ubuntu) で -std=c++0x フラグを設定して GCC4.7 を使用しています]

4

1 に答える 1

-1

クラスの.hファイルメンバー:

static CSingleton s_Instance;

インクルード直後の最初の.cppファイル

CSingleton::s_Instance = CSingleton();

これはコンパイル時の初期化です。new を使用 - これは実行時の初期化です。形式的には両方ともコンパイル時に初期化します。

于 2012-04-12T12:33:36.643 に答える