Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!netnews.upenn.edu!chin From: chin@sg1.chem.upenn.edu (Chin Wu) Newsgroups: comp.lang.c++ Subject: Borland C++ bug? Message-ID: Date: 2 Aug 90 05:19:54 GMT Sender: news@netnews.upenn.edu Distribution: comp Organization: University of Pennsylvania, Philadelphia, PA Lines: 67 Following codes illustrate a possible bug in temporary objects handling by Borland C++ compiler. **** code followed **** #include 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