// (C) Porkolab 2003 // // A.4.7. // // Temporaries Temporary objects: - Created under the evaluation of an expression - Destroyed when full expression has been evaluated void f( string &s1, string &s2, string &s3) { const char *cs = (s1+s2).c_str(); cout << cs; // Bad!! if ( strlen(cs = (s2+s3).c_str()) < 8 && cs[0] == 'a' ) // Ok cout << cs; // Bad!! } // the correct way: void f( string &s1, string &s2, string &s3) { cout << s1 + s2; string s = s2 + s3; if ( s.length() < 8 && s[0] == 'a' ) cout << s; } // another correct way: void f( string &s1, string &s2, string &s3) { cout << s1 + s2; const string &s = s2 + s3; if ( s.length() < 8 && s[0] == 'a' ) cout << s; // Ok } // s1+s2 destroyes here: when the const ref goes out of scope