5
//file1.cpp
extern const char* foo;
std::string bar = foo;

//file2.cpp
const char* foo = "foo";

Is bar guaranteed by the standard to be initialized to "foo"? Or could it be initialized before foo gets set and segfault in the constructor i.e. a case of SIOF?

  • I don't think it's irrelevant since I've seen some quirks in the rules for converting string literals to pointers before (especially relating to `constexpr`) so it might be a special case here too. – Artikash-Reinstate Monica Aug 12 '19 at 11:23
  • Related: https://stackoverflow.com/questions/29312371/c-static-variables-initialization-order (I still expect that there is a dupe somewhere). – Max Langhof Aug 12 '19 at 11:24

1 Answers1

8

Constant initialization is guaranteed to happen first (foo in this case).

So

Is bar guaranteed by the standard to be initialized to "foo"?

Yes.

Or could it be initialized before foo gets set and segfault in the constructor i.e. a case of SIOF?

No.

Source: https://en.cppreference.com/w/cpp/language/constant_initialization

Nestor
  • 652
  • 3
  • 12
  • How is this answer different to mine? "If in your case both are global, the std::string bar will always be initialised to "foo" because bar depends on foo during the compiler stage" – Nina Aug 12 '19 at 11:31
  • 3
    I am concerned that this is wrong. See https://stackoverflow.com/questions/29312371/c-static-variables-initialization-order and http://eel.is/c++draft/basic.start#static-3. – Max Langhof Aug 12 '19 at 11:32
  • Thanks! I'll edit the reply in the moment. The variable is non-static, it is merely const. – Nestor Aug 12 '19 at 11:39
  • @Rakete1111 Is it guaranteed that no early dynamic initialization happens here? I can't wrap my head around http://eel.is/c++draft/basic.start#static-3.2... – Max Langhof Aug 12 '19 at 11:49
  • @MaxLanghof In practice this doesn't happen though because compilers don't see across TUs :) – Rakete1111 Aug 12 '19 at 11:49
  • @Rakete1111 Well, link time optimization is a thing, no? – Max Langhof Aug 12 '19 at 11:49
  • @MaxLanghof The example is explained better in cppreference, see if that clears up your questions :). I have no idea if LTO does that. – Rakete1111 Aug 12 '19 at 11:50