c++initialization-order

Using a free "char const*" at static initialization time


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?

Aside from that: what if str was of type "char const[]"? And if it was a std::string?


Solution

  • The initialisation order is defined - they are initialised in the order they appear in a compilation unit - see section 3.6.2 of the C++ Standard. The type of the things being initialised has no effect.