是否可以使用静态变量初始化/注册变量? [英] Is it ok to use a static variable to initalize/register variables?

查看:161
本文介绍了是否可以使用静态变量初始化/注册变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

语言:C ++
工具包:Qt4

Language: C++ Toolkit: Qt4

我使用的工具包有一个静态方法 int QEvent :: registerEventType ()来注册我自己的事件类型。当我子类这个 QEvent 我需要提供基类这个值。 QEvent :: QEvent(int type)

The toolkit I'm using has a static method called int QEvent::registerEventType() to register my own event types. When I subclass this QEvent I need to supply the base class this value. QEvent::QEvent(int type).

在应用程序之前使用静态变量调用开始?请考虑以下内容:

Is it ok to use a static variable to call this before application starts? Consider the following:

//This is all in my .cpp file

static int myEventType;  //This will contain my registered type

/*If I create a static instance of this class the constructor 
  gets called before the main() function starts.
*/
class DoRegisterMyEventType {  
public:
  DoRegisterMyEventType() {
    myEventType = QEvent::registerEventType();
  }
};

static DoRegisterMyEventType doRegisterMyEventType;

//Here is the constructor for MyEvent class which inherits QEvent.
MyEvent::MyEvent()
  : QEvent(myEventType)
{
}

这是什么'邪恶'?

推荐答案

静态级别初始化是一个巨大的编译器依赖灰色区域,如其他人提到的。但是,函数级初始化不是一个灰色区域,可以用于您的优势。

Static level initialization is a huge compiler-dependent grey area, as others have mentioned. However, function level initialization is not a grey area and can be used to your advantage.

static inline int GetMyEventType()
{
    static int sEventType = QEvent::registerEventType();
    return sEventType;
}

MyEvent::MyEvent()
  : QEvent(GetMyEventType())
{
}

这个解决方案有一个属性,即registerEventType被保证在你需要你的事件类型之前被调用,即使你在静态初始化时构造MyEvent,但是如果可以在多个线程上构建MyEvent,它会打开线程安全问题。

This solution has the property that registerEventType is guaranteed to be called before you need your event type even if you construct MyEvent during static initialization, which is good, but it does open you up to thread-safety issues if it's possible for MyEvent to be constructed on multiple threads.

这里是一个线程安全的版本,基于boost :: call_once:

Here's a thread-safe version, based on boost::call_once:

#include "boost/thread/once.hpp"

static boost::once_flag sHaveRegistered = BOOST_ONCE_INIT; //This is initialized statically, effectively at compile time.    
static int sEventType = -1; //-1 is not a valid event

static void DoRegister()
{
    sEventType = QEvent::registerEventType();
}

static inline int GetMyEventType()
{
    boost::call_once(sHaveRegistered, &DoRegister);
    return sEventType;
}

这篇关于是否可以使用静态变量初始化/注册变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆