//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?
the initializations are the same: the ctor of std::string sets it to the empty string.
The standard advice in c++ is always initialize all your variables. So yes, you should initialize it. That's just good practice.
std::string literals are Standard Library implementations of user-defined literals (see below) that are represented as "xyz"s (with a s suffix). This kind of string literal produces a temporary object of type std::string , std::wstring , std::u32string , or std::u16string , depending on the prefix that is specified.
The best way to declare a string literal in your code is to use array notation, like this: char string[] = "I am some sort of interesting string. \n"; This type of declaration is 100 percent okey-doke.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With