2

A minimal example follows:

#include <map>
#include <string>

static const std::map<std::string,int> myMap= {
 {"a",1},{"b",2},{"c",3},{"d",4}
}

static const std::map<std::string,int> secondMap(myMap); /*(1)*/

int main(){
  return 0;
}

When is the above map initialized?

My best guess is that it should be initialized before the call of main, but I couldn't find relevant text in the standard.

Can myMap be used by any other static variables without invoking undefined behavior? point /*(1)*/ demonstrates a possible usage.

Does the behavior change when the map is in a header file, instead of a translation unit?

I understand that there are different initialization phases for static variables in a C++ program, but the linked question does not answer which category the variable in the example belongs to.

My guess is that because it is constant, it would be static initialization, but honestly I'm not sure.

Dávid Tóth
  • 2,788
  • 1
  • 21
  • 46
  • https://stackoverflow.com/questions/17783210/when-are-static-and-global-variables-initialized should help – The Apache Apr 27 '22 at 07:44
  • In this program, potentially never. Nothing odr-uses it. – StoryTeller - Unslander Monica Apr 27 '22 at 07:45
  • https://en.cppreference.com/w/cpp/language/initialization#Non-local_variables – 273K Apr 27 '22 at 07:46
  • I Update the question to reflect the suggestions. – Dávid Tóth Apr 27 '22 at 07:51
  • `myMap` won't be zero-initialized, you provide explicit initializer to it. It will be initiliazed with what you gave, at some point before `main()` is called. – Yksisarvinen Apr 27 '22 at 07:53
  • About the headers, compiler never "sees" them, `#include` is fancy word for copy paste. Of course including something twice then equals potentially defining something twice -> ODR violation. – Quimby Apr 27 '22 at 07:59
  • The second paragraph of the accepted answer to the proposed duplicate should answer your main question, as long as you realize that the constructor of your map needs to be called. For your secondary questions, a key phrase for you to look up is "[tag:static-order-fiasco]" -- or you could just trust the last word of that and guess... ;) – JaMiT Apr 27 '22 at 08:06
  • https://en.cppreference.com/w/cpp/language/siof this link states that inside the same translation uinit static initialization is from top to bottom; Trouble would start in different compilation units. – Dávid Tóth Apr 27 '22 at 08:11
  • @DávidTóth *"Trouble would start in different compilation units"* -- right. And you can rely on that if you want. As long as no one will ever decide your source file warrants being split into two.... ;) – JaMiT Apr 28 '22 at 05:08
  • I would definitely not want to :D – Dávid Tóth Apr 28 '22 at 07:59

0 Answers0