tags:

views:

94

answers:

3

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?

+2  A: 

Yes. (It isn't different of storing such pointer in a global data structure).

AProgrammer
+6  A: 

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.

Prasoon Saurav
+3  A: 

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.

Philip Potter
@Philip: I tried this out in VS2008 and I got no warning. I don't know if there is a warning for this. Maybe there is and its turned off by default because so much of the supplied headers would trigger the warning ;-)
quamrana