When the function returns a string, we can define a return of string and string&.
1 Write a function that returns a string reference
std::string & TestStringReference(){ std::string"holy shit"; return loal_str;}
This function is, of course, wrong and the compiler will prompt us:
Returns the address of a local variable or temporary variable: loal_str
That is, you cannot return a reference to a local variable.
2 Write a function that returns a string that can not be referenced when the function returns a local variable string? )
std::string TestStringReference(){ std::string"This is a test."; return strTest;}
So can the return value of the above function be referenced?
Code to speak:
#include <iostream> #include <string> std :: Span class= "hljs-built_in" >string teststringreference () {std :: string strtest = "This is a test." ; return strtest;} int Main () {std :: string & strrefer = Teststringreference (); std :: cout << "Strrefer:" << strrefer << std :: Endl return 0 ;}
The code works perfectly.
Instead of a local variable, the compiler's newly constructed temporary object is actually returned.
3 A function that returns a string is called directly. C_STR ()
As stated above, the returned "local" string can be referenced, then the returned "local" string is called directly. C_STR () What's the effect, eh?
#include<iostream>#include<string>std::string TestStringC_STR(){ std::string"This is a test."; return strTest;}int main(){ constchar *pc = TestStringC_STR().c_str(); std::coutstd::endl; return0;}
The above code compiler will not error!
But wait, don't be happy too early, look at the output, empty, not what we expected.
The point is that instead of assigning the result of Teststringc_str () to a string object to get its pointer directly, the system does not call a copy constructor or assignment function for string, and the returned string is still just the state of a temporary object. It will be destroyed upon completion of the assignment to the PC, and its internal data will not exist.
Workaround: First use a string to receive the return value of the function, and then call the C_str () method:
#include <iostream> #include <string> std :: Span class= "hljs-built_in" >string teststringc_str () {std :: string strtest = " This is a test. "; return strtest;} int Main () {std :: string str1 = Teststringc_str (); const char *pc = Str1.c_str (); std :: cout << pc << STD :: Endl; return 0 ;}
String Series in combat C + +-function returns a local variable string (A. C_str () function that references a local string, local string)