Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!pacbell.com!tandem!zorch!vsi1!octopus!sjsumcs!horstman From: horstman@mathcs.sjsu.edu (Cay Horstmann) Newsgroups: comp.lang.c++ Subject: Re: Incorrect handling of destructors in Turbo C++ Keywords: Turbo C++, destructors Message-ID: <1991Mar25.231208.29589@mathcs.sjsu.edu> Date: 25 Mar 91 23:12:08 GMT References: <546@humu.NOSC.Mil> Organization: San Jose State University - Math/CS Dept. Lines: 69 In article <546@humu.NOSC.Mil> you write: >There seems to be a bug in the code that Turbo C++ 1.00 generates. >In the following program the destructor routine should only be called >once. > >------------ ># include > >class A { > protected: > int i; > public: > A(); > ~A(); >}; > >A::A() >{ > printf("Constructor called\n"); >} > >A::~A() >{ > printf("Destructor called\n"); >} > >void sub(A a) >{ > printf("in sub\n"); >} > >void main() >{ > A a; > > printf("before call\n"); > sub(a); > printf("after call\n"); >} >------------ > >When this program is executed: > >------------ >Constructor called >before call >in sub >after call >Destructor called >Destructor called >------------ > You are wrong. You didn't supply a copy constructor for A (i.e. no A(const A&)). That made the argument in sub constructed with a bitwise copy but destroyed with the ~A(). The only funny thing is that Turbo routinely translates a function call sub(a) into A temp = a; sub( temp ) and changes void sub( A a ) into void sub( A& a ). It beats me why they do it, but they do, and that is why the destructor is called both times after sub exits. I ran into some cases when the destructor didn't get called enough, but I have a hard time reproducing it in a small and short program. If anyone has one, let me know! Cay