Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!cs.utexas.edu!uunet!mcvax!hp4nl!kunivv1!atcmpe!leo From: leo@atcmp.nl (Leo Willems) Newsgroups: comp.lang.c++ Subject: Re: Constructors and new Message-ID: <523@atcmpe.atcmp.nl> Date: 1 Jun 89 22:39:24 GMT References: Organization: AT Computing, Nijmegen, The Netherlands Lines: 84 > >Dave Geary asks why this program: > > >>class testclass >>{ >> public: >> >> testclass() { if(this == 0) puts("Used new..."); else puts("Did not use new..."); } >> ~testclass() { puts("I'm a destructor..."); } >>}; >> >>main() >>{ >> testclass var; >> new testclass; >>} > >produces this output: > >>Did not use new... >>Did not use new... >>I'm a destructor... In the paper `the evolution of C++ 1985 to 1987' Bjarne Stroustrup gives a more detailed example of the way how to use the -this- pointer in a constructor when allocating memory yourself. (versus par. 5.5.7 in the C++ P.L.) Somewhere (I can't find it right now) it is mentioned that the assignment to the -this- pointer in the constructor should be made on every possible execution path. The following code does not suffer from the problem above: extern char*malloc(int); extern void free(char*); class testclass { private: int used_new; public: testclass(); ~testclass(){ if (used_new){ free((char*)this); this = 0; // this assignment must be done } puts("I'm a destructor..."); } }; testclass::testclass() { if (this == 0){ puts("Used new..."); this = (testclass*) malloc(sizeof(testclass)); // this assignment must be done used_new = 1; //assigment after allocation! } else { used_new = 0; puts("Did not use new..."); this = this; // this assignment must be done } } main() { testclass var; new testclass; } This solution leaves me with a question too. Shouldn't the destructor also assign on every possible path to the -this- pointer? Leo Willems Internet: leo@atcmp.nl AT Computing UUCP: mcvax!hp4nl!kunivv1!atcmpe!leo P. O. Box 1428 6501 BK Nijmegen The Netherlands