* Today I read the C ++ programming language (Special Edition) inventor's description of temporary objects. Although it is a small section, I feel that C ++ books, the content is still the most authoritative, and many things in it are expressed with definite authority and conviction.
The survival time limit of a temporary object only takes a short chapter in this book, but it is clear that the survival time limit of the temporary object is limited to the "complete" expression in its appearance, the "complete" expression ends, and the temporary object is destroyed. The exception is to reference or initialize a temporary object to a named object. The life cycle of the temporary object is extended to the life cycle of the referenced or named object.
The short program below tests the survival time limit of the temporary object. vs2005 demonstrates that the temporary object is destroyed after its "complete" expression ends.
*/
# Include <iostream>
# Include <string>
Using namespace STD;
/* Print the string */
Void print (const string & Str)
{
Cout <Str. c_str () <Endl;
}
/* Print string 2 */
Void display (string Str)
{
Cout <"XXXXXXXX" <Endl;
Cout <Str. c_str () <Endl;
Cout <"XXXXXXXX" <Endl;
}
Int main ()
{
String str1 = "Xiaocui ";
String str2 = ", nihao ";
Const char * s = NULL;
If (S = (str1 + str2 ). c_str () // S1 + S2 generates a temporary String object. Its life cycle is the life cycle of the complete expression of the temporary object.
{
Cout <S <Endl; // The temporary object above has been parsed after its "complete" expression, so the memory that s points to does not exist, s referenced here is undefined and dangerous.
}
String Ss = str1 + str2; // str1 + str2 also generates a temporary object, but it is used to initialize the named object. Therefore, the life cycle of the temporary object is extended to the period of the named object.
Cout <ss. c_str () <Endl; // correct output indicates that the temporary object still exists and has not been destroyed. The storage of the stored strings is normal (# add, I do not think so, SS is another object, but it will be initially assigned by str1 + str2. It has nothing to do with the temporary object itself. The output is only SS, and it does not indicate that str1 + str2 is still in progress .)
Print (str1 + str2); // pass the temporary object generated by str1 + str2 to the cosnt reference. The life cycle of the temporary object is extended to the life cycle of the const reference, so it is printed normally.
Display (str1 + str2); // function transmission has initialization semantics, so the temporary object generated by str1 + str2 initializes STR, and the lifecycle is prolonged, which is printed normally.
Return 0;
}
If you do not go into details, the following sentence can be used as a general impression:
The temporary object is valid only for the current row.
The partial object is valid until the end of the function.