Reputation: 29970
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.
Upvotes: 4
Views: 322
Reputation: 425
I believe it would be also in msvc (at least vs 2015) if you were to declare the f itself as constexpr Foo f;
Upvotes: 0
Reputation: 10073
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.
Upvotes: 0
Reputation: 72431
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 invokeconstexpr
constructors foro
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
.
Upvotes: 3