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?
std::string_view
suffices if you don't need a fullstd::string
. Of course it still has the same lifetime requirements since it doesn't use its own storage. – Carissacaritachar*
argument to the function. – Crispation