Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 255
Bernard Avatar asked Dec 20 '17 05:12

Bernard


1 Answers

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.

like image 74
songyuanyao Avatar answered Nov 07 '22 13:11

songyuanyao