Path: utzoo!utgpu!watmath!watcgl!andrewt From: andrewt@watsnew.waterloo.edu (Andrew Thomas) Newsgroups: gnu.g++.bug Subject: Destructor called too soon, Destructor not called - G++1.35 Message-ID: Date: 3 Aug 89 04:11:06 GMT Sender: daemon@watcgl.waterloo.edu Distribution: world Organization: University of Waterloo, Waterloo, Ontario, Canada Lines: 88 System: uVax II , Ultrix 2.0 G++ 1.35 Problem: The destructors for class instances passed as return values (rather than returning a pointer or reference) get called too soon if only a member of the class is of interest. Also, sometimes no destructor is called at all. Program: The following program exhibits both behaviours described above: ----------------- cut ---------------------------- #include class String { char *_ptr; public: String (String&); String (char *); ~String(); char* ptr() { return (_ptr); } }; String::String (String& old) { char* a = new char[strlen(old._ptr) + 1]; strcpy (a, old._ptr); _ptr = a; printf ("Constructing: %s (%x)\n", a, a); } String::String (char* old) { char* a = new char[strlen(old) + 1]; strcpy (a, old); _ptr = a; printf ("Constructing: %s (%x)\n", a, a); } String::~String() { printf ("deleting %s (%x)\n", _ptr, _ptr); delete _ptr; } String my_func () { String x = "Hello"; return (x); } main () { printf ("Function: %s (%x)\n", my_func(), my_func()); printf ("Function: %s (%x)\n", my_func().ptr(), my_func().ptr()); } ------------------------- cut ------------------------- The output of this program looks like: Constructing: Hello (1c00) Constructing: Hello (1c10) deleting Hello (1c00) Constructing: Hello (1c00) Constructing: Hello (1c20) deleting Hello (1c00) Function: Hello (1c10) Constructing: Hello (1c00) Constructing: Hello (1c30) deleting Hello (1c00) deleting Hello (1c30) Constructing: Hello (1c30) Constructing: Hello (1c00) deleting Hello (1c30) deleting Hello (1c00) Function: Hello (1c30) Note only 6 destructors, and 8 constructors. Also note that memory address 1c30 is deleted with an automatically called destructor before the String instance is actually used. -- Andrew Thomas andrewt@watsnew.waterloo.edu Systems Design Eng. University of Waterloo "If a million people do a stupid thing, it's still a stupid thing." - Opus