Using the free "char const *" with static initialization time

The initialization order of free objects is undefined in C ++. But what about the following?

namespace foo { char const* str = "hey"; struct A { A() { cout << str; } } obj; } 

Is this still undefined behavior or is there a special provision for pointers initialized with string literals?

Besides this : what if str is of type "char const []"? And if it was std :: string?

+1
source share
2 answers

The initialization order is defined - they are initialized in the order in which they appear in the compilation module - see section 3.6.2 of the C ++ Standard. The type of initialized objects is not affected.

+3
source

Even if they are located in different translation units, the initialization order is still defined.

This is because str initialized with an address constant expression , and str is of type pod. That would be true if you had an array. But that would not be true if you had std::string . They are dynamically initialized (since std::string is a non-POD).

Thus, if your str was std::string , you would encounter undefined behavior if obj defined in a different translation unit, but the only case from the one you specified that would cause the problem is

+5
source

Source: https://habr.com/ru/post/905254/


All Articles