chin@sg1.chem.upenn.edu (Chin Wu) (08/02/90)
Following codes illustrate a possible bug in temporary objects handling by Borland C++ compiler. **** code followed **** #include <iostream.h> class String { int len; char *st; public: friend ostream& operator << (ostream& out, String& s); String(char *s); String(String& s); ~String(void) { cout << "Destructor\n"; delete st; }; }; inline ostream& operator << (ostream& out, String& s) { out << s.st; return out; }; String::String(char *s) { len = strlen(s); st = new char[len + 1]; strcpy(st, s); cout << "Constructor A\n"; }; String::String(String& s) { len = s.len; st = new char[len + 1]; strcpy(st, s.st); cout << "Constructor B\n"; }; String test(void) { return String("Hello"); }; main() { String d = test(); cout << d << '\n'; }; **** result followed **** Constructor A Constructor B Constructor B Destructor Destructor ************************** There is one less Destructor has been called and the content of the temporary String object has lost, "Hello" in this case. To work around the problem I have to declare a variable in String test(void); like: String test(void) { String stupid = "Hello"; return stupid; }; Am I understand C++ wrong? Thanx in advance. Chin -- chin@sg1.chem.upenn.edu