简体   繁体   English

在编译时单例初始化

[英]Singleton initialization at compile-time

I was just thinking if the new C++11 in-class member initializers could be used to initialize Singletons at compile-time, which might be a speed-up for some Manager-Classes in my applications: 我只是在考虑新的C ++ 11类内成员初始化器是否可以用于在编译时初始化Singletons,这可能是我的应用程序中某些Manager-Classes的加速:

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();
}

The problem is this results in following errors: 问题是导致以下错误:

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'

Is there a way to initialize Singletons during compile-time with this or another approach? 有没有办法在编译时使用这种或另一种方法初始化单身人士?

[I am using GCC4.7 on MacOSX10.7 (and Ubuntu) with -std=c++0x flag set] [我在MacOSX10.7(和Ubuntu)上使用GCC4.7并设置-std = c ++ 0x flag]

in .h file member of class: 在.h文件类成员:

static CSingleton s_Instance;

in .cpp file in the begining right after include 在包含后的开头右边的.cpp文件中

CSingleton::s_Instance = CSingleton();

This is initialization in compile time. 这是编译时的初始化。 using new - this is initialization in runtime. 使用new - 这是在运行时初始化。 Formally both of them initialization in compile time. 正式地,它们都在编译时初始化。

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

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