Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

c++ - If a global variable is initialized twice (statically, then dynamically), which initialization starts its lifetime?

Inspired by this question.

We know that global variables with non-constexpr initializers undergo two different "initializations":

  • First, the "static initialization", which zero-initializes them.
  • Second, the "dynamic initialization", which uses the user-provided initializer.

Which of those initializations starts the variable lifetime? [basic.life] is being surprisingly unhelpful:

The lifetime of an object ... begins when: ... its initialization (if any) is complete

I see several options:

  1. The last initialization starts the lifetime.
  2. The first initialization starts the lifetime.
  3. Each successive initialization destroys the existing object and creates a new one in its place.

(1) Would make the most sense, but it would make the static initialization of an object that will later be dynamically initialized mostly useless.

(2) Would have interesting effects. E.g. the static init order fiasco is suddenly not UB (by itself) anymore.

(3) Would be very weird.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Indeed, the standard is vague by not specifying how exactly the quoted rule "initialization (if any) is complete" applies to multiple stages of initialization, each of which being referred to as "initialization". And this leaves room for multiple interpretations.

This footnote (non-normative) implies that the lifetime begins only after dynamic initialisation is complete:

[basic.life]

Before the lifetime of an object has started but after the storage which the object will occupy has been allocated 26 ...

26 For example, before the dynamic initialization of an object with static storage duration ([basic.start.dynamic]).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...