简体   繁体   中英

Is returning a string literal address from a function safe and portable?

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM