Q_GLOBAL_STATIC

Creating C++ classes in global space is generally a bad idea, because the order of construction is undefined. On top of that, constructors require execution, thus slowing down your program startup time. Enter Q_GLOBAL_STATIC. It works like this:

Q_GLOBAL_STATIC(Foo, get_foo)

Write this in your global space, and it will define a function called get_foo() that essentially does “new Foo” (if it has not done so already) and returns it. Now, instead of using the object directly, you use the function. This puts you in control of when your global objects are created, and gives you lazy-loading to boot. An atomic integer operation is used for thread-safe construction. In addition, a static template class “wrapper” is defined for your type, so that your object will be properly destructed on exit, just like a normal global type. Granted, this is a slight bit of overhead, but probably less than any object you’d use it with. There’s even Q_GLOBAL_STATIC_WITH_ARGS().

You probably shouldn’t be using globals anyway, but sometimes you need them. Q_GLOBAL_STATIC seems particularly useful with QMutex, the bare-minimum to get you off the ground for creating thread-safe singletons.

2 Comments »

  1. Sebastian said,

    January 18, 2008 @ 7:00 am

    Interesting, thanks for writing about this.

  2. Etrnls said,

    January 31, 2008 @ 5:55 am

    Thx~ It’s useful !

RSS feed for comments on this post · TrackBack URI

Leave a Comment

Bad Behavior has blocked 322 access attempts in the last 7 days.