In practice, the string series in c ++ -- function returns the local variable string (referencing the local string, the. c_str () function of the local string)
When the function returns a string, we can define the return string and string &.
1. Write a function that returns a string reference.
std::string & TestStringReference(){ std::string loal_str = "holy shit"; return loal_str;}
Of course this function is incorrect. The compiler will prompt us:
Return the address of the local or temporary variable: loal_str
That is, local variables cannot be referenced.
2. Write a function that returns the string (can the function be referenced when returning the local variable string ?)
std::string TestStringReference(){ std::string strTest = "This is a test."; return strTest;}
Can the returned values of the above functions be referenced?
Code statement:
#include
#include
std::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 runs perfectly.
In fact, the returned result is not a local variable, but a temporary object newly constructed by the compiler.
3. Return the string function and call. c_str () directly ()
As mentioned above, if the returned "local" string can be referenced, What effect will the returned "local" string be called directly. c_str?
#include
#include
std::string TestStringC_STR(){ std::string strTest = "This is a test."; return strTest;}int main(){ const char *pc = TestStringC_STR().c_str(); std::cout << pc << std::endl; return 0;}
The above code compiler will not report an error!
But wait. Don't be too happy. Let's look at the output result. It's blank, not what we expect.
The key is that we did not assign the result of TestStringC_STR () to a string object to directly obtain its pointer. At this time, the system will not call the copy constructor or assign a value to the string, the returned string is still the state of a temporary object. It will be destroyed after the value is assigned to the pc, and its internal data will not exist.
Solution: first use a string to receive the return value of the function, and then call the c_str () method:
#include
#include
std::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;}