Returning const char* from a string literal in C++?

2.2k Views Asked by At

Normally, I would return a std::string from a function because returning a const char* would require the caller to provide an output memory buffer, and that buffer is not resizable.

But is returning a const char* valid if its from a string literal?

const char* generate_c_string() {
    return "ABC";
}

Doing in this way (if valid) would likely be faster as I would not need to dynamically allocate memory to construct a std::string.

It probably is valid, because const char* x = "ABC"; is valid. Is there a reference from the C++ standard that substantiates its validity?

1

There are 1 best solutions below

2
On BEST ANSWER

This is valid, for string literals,

String literals have static storage duration, and thus exist in memory for the life of the program.

The pointer returned would remain valid in the life of the program.