charlie@genrad.com (Charlie D. Havener) (07/06/90)
// Weird Borland Turbo C++ BUG! Calls destructor for local object twice! #include <iostream.h> #include <fstream.h> #include <stdlib.h> class Trace { const char *name; // points to the string arg in the code body static int spaces; // space over this much before printing out trace msg public: Trace(const char *fname); ~Trace(); }; class Foobar { int k; public: Foobar(int i = 0 ) { k = i; } ~Foobar() { Trace trace("~Foobar"); } // Note that this destructor causes a Trace object to // be created and destroyed. }; //---------------------------------------------------------------------------- main() { Foobar y; // Borland calls destructor TWICE! // This results in zillions of spaces being sent // to the output stream from the ~Trace below. // Happens on my 286 Clone and on a 386 // Works fine on Sun C++ 2.0 } //--------------------------------------------------------------------------------- Trace::Trace(const char *p) { name = p; int i = spaces; spaces+=2; while ( i-- ) cout << " "; cout << "enter " << p << '\n'; } Trace::~Trace() { spaces-=2; int i = spaces; while ( i-- ) cout << " "; cout << "leave " << name << '\n'; } // Many thanks to Craig Dawson at GenRad for confirming this bug // on his 386 PC. Extensive analysis with the Turbo debugger // whittled this down from a much larger program to what you see // above. // Charlie Havener at GenRad Inc. 300 Baker Ave. Concord. Mass. // charlie@genrad.com