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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With