In C
, you can write
const char *result = "AB";
Is this style supported in C++
by standard? Is the life-time of this constant string guaranteed along with the same scope of the pointer?
In C
, you can write
const char *result = "AB";
Is this style supported in C++
by standard? Is the life-time of this constant string guaranteed along with the same scope of the pointer?
Literals string constants have a lifetime of the whole program, and the arrays the strings are stored in never go out of scope.
Note that there's a semantic difference between literal strings in C and C++: In C++ literal strings are stored in arrays of constant characters (therefore the const
in const char*
is needed). In C they aren't constant arrays (so char *
is alright in C). However, it's not allowed to modify a literal string in C, which makes them read only (but not constant).
Is the life-time of this constant string guaranteed along with the same scope of the pointer?
No, the lifetime of string literals has nothing to do with the lifetime of pointers pointing to them; String literals exist in the whole life of the program.
String literals have static storage duration, and thus exist in memory for the life of the program.
6 After translation phase 6, a string-literal that does not begin with an encoding-prefix is an ordinary string literal. An ordinary string literal has type “array of n const char” where n is the size of the string as defined below, has static storage duration ([basic.stc]), and is initialized with the given characters.
15 Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. ...
Quoting C++17
, chapter § 5.13.5 (emphasis mine)
Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration
and, for static storage duration, chapter § 6.7.1
All variables which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these entities shall last for the duration of the program.
So, the lifetime of the string literals is the entire execution of the program, it never goes out of scope.
The string constant (literal) has the same lifetime as the whole program. From way before the pointer is created to long after it's destroyed