15

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?

sharptooth
  • 167,383
  • 100
  • 513
  • 979

3 Answers3

14

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
  • 91,295
  • 49
  • 239
  • 345
10

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
  • 8,975
  • 2
  • 37
  • 47
  • @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 Mar 03 '10 at 14:11
3

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

AProgrammer
  • 51,233
  • 8
  • 91
  • 143