Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 474
Artikash-Reinstate Monica Avatar asked Aug 12 '19 11:08

Artikash-Reinstate Monica


People also ask

Is std::string initialized to empty?

the initializations are the same: the ctor of std::string sets it to the empty string.

Do we need to initialize string in C++?

The standard advice in c++ is always initialize all your variables. So yes, you should initialize it. That's just good practice.

Is std::string literal?

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.

How do you initialize a string literal?

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.


1 Answers

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

like image 188
Nestor Avatar answered Sep 19 '22 18:09

Nestor