简体   繁体   中英

Is static initialization guaranteed here?

Look at this code:

struct Foo {
        void *ptr;

        constexpr Foo() : ptr(nullptr) { }
};

Foo f;

Is it guaranteed that f will be statically initialized?

Clang uses static initialization here, but MSVC doesn't .

Yes, the Standard says f will be constant initialized:

[basic.start.init]/2:

A constant initializer for an object o is an expression that is a constant expression, except that it may also invoke constexpr constructors for o and its subobjects even if those objects are of non-literal class types [ Note: such a class may have a non-trivial destructor -- end note ]. Constant initialization is performed:

  • ... [a case for references]

  • if an object with static or thread storage duration is initialized by a constructor call, and if the initialization full-expression is a constant initializer for the object;

  • ... [a case for objects initialized without a constructor call]

Together, zero-initialization and constant initialization are called static initialization ; all other initialization is dynamic initialization . Static initialization shall be performed before any dynamic initialization takes place.

The initialization full-expression is simply the call of Foo 's default constructor, which is a constant expression.

MSVC is wrong to emit code to initialize f .

Standard-wise, yes. Reality-wise, no.

You are at the mercy of compiler venders when it comes to static initialization compliance.

[edit] Clang is a special compiler — from the beginning its creators have been interested in full standards compliance.

如果你要将f本身声明为constexpr Foo f,我相信它也会在msvc中(至少对2015年);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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