Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!nrl-cmf!ames!apple!bloom-beacon!mit-eddie!apollo!vasta From: vasta@apollo.COM (John Vasta) Newsgroups: comp.lang.c++ Subject: Re: Constructors and new Message-ID: <43984c6e.1ad5a@apollo.COM> Date: 2 Jun 89 19:20:00 GMT References: <2684@ssc-vax.UUCP> Reply-To: vasta@apollo.COM (John Vasta) Organization: Apollo Computer, Chelmsford, MA Lines: 73 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" ~ >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Checking the value of 'this' only makes sense if you want to assign to it. The statement from The Book is in the section about taking over the storage allocation mechanism; the first sentence in 5.5.7 is "When assigning to this in a constructor, the value of this is undefined until that assignment." If you don't assign to this, the compiler synthesizes code to do so (if this == 0). The code is inserted at the beginning of the constructor, so the first statements you write are guaranteed to never see this == 0, unless you assign to this somewhere, or there's some sort of storage allocation failure. If you change the constructor to read: testclass() { if(this == 0) puts("Used new..."); else puts("Did not use new..."); this = this; } then the output from the program is: Did not use new... Used new... I'm a destructor... -- John Vasta Apollo Computer, Inc. vasta@apollo.com M.S. CHA-01-LT (508) 256-6600 x6362 330 Billerica Road, Chelmsford, MA 01824 UUCP: {decwrl!decvax, mit-eddie, attunix}!apollo!vasta