Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 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 Answer

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]).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...