Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!cs.utexas.edu!uunet!mcvax!ukc!warwick!expya!msor!kt From: kt@msor.UUCP (Keith Tizzard) Newsgroups: comp.lang.c++ Subject: Re: Constructors and new Message-ID: <363@msor0.UUCP> Date: 2 Jun 89 14:02:00 GMT Sender: Keith Tizzard Reply-To: kt@msor.UUCP (Keith Tizzard) Organization: MSOR Department, Exeter University, UK Lines: 85 In article <2684@ssc-vax.UUCP> dmg@ssc-vax.UUCP (David Geary) writes: : : According to BS, section 5.5.7, a constructor for a class can determine whether :it was called by new or not. : :"If it is called by new, the pointer this has the value zero at entry, :otherwise this points to space already allocated for the object..." : : Ok, so what does the following print? : :#include : :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; :} : :Output: : :Did not use new... :Did not use new... :I'm a destructor... : : This tells me one of two things: : : 1) I've found a bug in the compiler. : 2) I don't know what the h*ll I'm doing. : : My ego tells me #1, but my experience tells me it has to be #2 ;-) : :-- :~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :~ David Geary, Boeing Aerospace, Seattle ~ :~ "I wish I lived where it *only* rains 364 days a year" ~ :~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Zortech C++ produces the following output:- Used new... Used new... I'm a destructor... : From: dld@F.GP.CS.CMU.EDU (David Detlefs) : References: <2684@ssc-vax.UUCP> : : : And in <2684@ssc-vax.UUCP> David Detlefs adds : : : : I believe I can explain this. Look at 'main.' The first line of the : output is caused by the constructor call to initialize 'var', a : stack-allocated automatic variable. The second line is caused by the : evaluation of the expression 'new testclass;' This *does* use new, so : why does it say it doesn't? Well if you look at testclass, you'll : find that sizeof(testclass) is 0. I would guess that the 'malloc' that : operator new is calling returns 0 when it is asked to allocate a : zero-sized object. Thus, 'this' is 0 on entry to the constructor. : Finally, the testclass destructor is called when 'var' goes out of : scope. So I added an integer in the private part of the class and Zortech then produced: Did not use new... Did not use new... I'm a destructor... So where does this get us? :-)