K_GLOBAL_STATIC and other macros

Thiago Macieira thiago at kde.org
Fri Apr 13 10:38:35 BST 2007


Jos van den Oever wrote:
> 2007/4/13, Thomas Zander <zander at kde.org>:
>> I'm looking for a way to;
>> init the static to zero initially;
>> Define a method like 'instance' or 'self' that either returns an
>> existing
>> one or creates a new one including some initialisation code.
>
> This is really easy:
> MyObject&
> MyObject::self() {
>     static MyObject object;
>     return object;
> }
>
> This ensures the object has been initialized properly, even if it is
> used in another global static objects initialization. Since 'new' is
> not called, deallocation is also handled properly. The only thing that
> is not guaranteed is the order in which the destructors  are called.

Other things not guaranteed:
1) thread safety
2) construction at all

Some architectures are broken and don't properly construct objects when
dlopen()ing modules/plugins. Always use K_GLOBAL_STATIC, since that's a
thread-safe construct-on-first-use.

I am not sure if the C++ standard requires function statics to be
constructed on first use only, or if they can be constructed at load time.

Destruction isn't guaranteed ever (think of crashing applications, etc).
Don't rely on it.

-- 
  Thiago Macieira  -  thiago (AT) macieira.info - thiago (AT) kde.org
    PGP/GPG: 0x6EF45358; fingerprint:
    E067 918B B660 DBD1 105C  966C 33F5 F005 6EF4 5358






More information about the kde-core-devel mailing list