Returns a local C string for a function with a return value of a C ++ string

The following code fragment compiles and runs without errors and with the expected output:

#include <string> #include <iostream> using namespace std; string getString() { char s[] = "Hello world!"; return s; } int main() { cout << getString() << endl; } 

My question is: will this always work? Usually, if you return a C-string that was declared locally, you can run some undefined behavior, but in this case it is a problem, because it is run through the string constructor and (presumably) copied to dynamic memory?

+7
c ++ string
source share
1 answer
  return s; 

This line is equivalent to:

 return std::string(s); 

And that will make a copy of the string, so that's fine.

link: http://en.cppreference.com/w/cpp/string/basic_string/basic_string (constructor # 5)

Creates a string with the contents initialized by a null-character copy of the character string pointed to by s.

Edit: Another detail. You mentioned

copied to dynamic memory?

And the answer maybe, maybe it doesn't really matter.

The semantics provided by std::string does not provide any specifications for this, it simply ensures that it can be copied / moved and is available in a consistent way. How this happens is up to the library developer.

In fact, popular std::string implementations use something called " S mall S tring O ptimization". If lines under a certain length are stored inside the line object itself.

+12
source share

All Articles