7

Let's consider this hunk of code that simply tries to initialize a map from a constexpr array:

#include <string>
#include <map>
#include <array>
#include <tuple>

constexpr std::array<std::pair<int, const char *>, 10> my_array {
    { { 0, "dd" },
    { 1, "dd" },
    { 2, "dd" },
    { 7, "dd" },
    { 8, "dd" },
    { 9, "dd" }}
   };

std::map<int, std::string> my_map(std::begin(my_array), std::end(my_array));

int main() {
    return my_map[0].size(); //dummy random operation
}

I know there is not way to predict initialization order for the two variables (my_array and my_map). That said, my_array is constexpr, thus should be available a compile time, thus there should be no "initialization order" problem at startup.

Is this code correct or does the initialization order problem remains?

2
  • 1
    Are we talking about a single translation unit? Oct 6, 2019 at 19:00
  • 1
    If you can confirm it is not a problem in a single translation unit, let's assume the array could be in another translation unit to have a complete answer :)
    – OznOg
    Oct 6, 2019 at 19:04

1 Answer 1

3

[basic.start.static/2]:

Constant initialization is performed if a variable or temporary object with static or thread storage duration is constant-initialized. [...] Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. All static initialization strongly happens before ([intro.races]) any dynamic initialization.

So, "Is this code correct?": Yes, as my_array is constant initialized, and this happens before dynamic initialization (my_map).

(This quote is from the current draft standard, but this rule exists for C++14 as well)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.