Is a pointer to string literal guaranteed to be initialized before a std::string?

//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?

Upvotes: 5

Views: 156

Answers (1)

Nestor
Nestor

Reputation: 747

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

Upvotes: 8

Related Questions