Using a free "char const*" at static initialization time
Asked Answered
E

2

1

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?

Elledge answered 26/4, 2009 at 11:39 Comment(0)
F
3

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.

Frontiersman answered 26/4, 2009 at 11:40 Comment(1)
-1: This is wrong. See #8750907Scrawly
D
5

Even if they would be located in different translation units, the initialisation order is still defined.

That is because str is initialized with a constant expression (address constant expression) and str has pod-type. It would still hold true if you had an array. But it would not be true anymore if you had a std::string. Those are dynamically initialized (because std::string is a non-POD).

Thus, if your str were a std::string, you would run into undefined behavior if obj is defined in a different translation unit, but that's the only case of the one you listed that would cause trouble.

Delorasdelorenzo answered 26/4, 2009 at 12:52 Comment(0)
F
3

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.

Frontiersman answered 26/4, 2009 at 11:40 Comment(1)
-1: This is wrong. See #8750907Scrawly

© 2022 - 2024 — McMap. All rights reserved.