开发者

static initialization in case of dependencies

开发者 https://www.devze.com 2023-04-09 15:41 出处:网络
Is the following code safe (given no guarantees of static initialization order?). In some library: class A {

Is the following code safe (given no guarantees of static initialization order?).

In some library:

class A {
    A() : x_ = 0 {
    }

    int add() {
        return ++x_;
    }
};

namespace S {
    static A a_;
}

#define ADD(varname) \
    namespace S { \
        static int v_##varname = a_.add(); \
    } 

Macro ADD will be used at multiple places. Is it guaranteed that a_ wi开发者_开发技巧ll be initialized before v_##varname for any ADD macro usage?


There is a common trick for your case if you want to guarantee:

namespace S { 

A & getA() {
   static A a; 
   return a;
}

} // namespace S

And

static int v_name = getA().add();


In the same translation unit/source file only, any uses of ADD after the definition of a_ will be executed after a_ is constructed. In any other translation unit (library or application) all bets are off in terms of ordering of initialization.

You can use one of the static local methods if needed.

See the FAQ: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.15

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号