Reputation: 170509
I need a function to return a string that will only be accessed read-only. The string contents is known at compile time so that I will use a string literal anyway.
I can return something like std::string
:
std::string myFunction()
{
return "string";
}
or return const char*
:
const char* myFunction()
{
return "string";
}
Is the second alternative safe and portable in this scenario?
Upvotes: 15
Views: 2324
Reputation: 92874
Is the second alternative safe and portable in this scenario?
Yes! The storage allocation of string literals is static and they persist for the lifetime of the application.
Upvotes: 14
Reputation: 9135
Yes! But beware of this potential gotcha:
char * myFunc() {
return "Constant string?";
}
Yes, you can convert a string literal to a non-const char *
! This will enable you to later break the world by trying to modify the contents of that char *
. This "feature" exists for legacy reasons -- string literals are older than const, and were originally defined as char *
in C.
g++ throws out an obnoxious warning for this, even in the default mode, thankfully. I don't know if VC++ throws out a warning just as eagerly.
Upvotes: 11
Reputation: 52314
Yes. (It isn't different of storing such pointer in a global data structure).
Upvotes: 3