Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!ucsd!sdd.hp.com!samsung!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c++ Subject: Re: operator++() and testing 'this' Message-ID: <482@taumet.com> Date: 19 Oct 90 18:01:15 GMT References: <1990Oct14.224706.1934@nowhere.uucp> <58242@microsoft.UUCP> <479@taumet.com> <58351@microsoft.UUCP> Organization: Taumetric Corporation, San Diego Lines: 45 jimad@microsoft.UUCP (Jim ADCOCK) writes: >There does exist some compilers that support the (this==0) test -- >provided you also perform the assignment to this hack. I guess this >is a case where two wrongs *do* make a right! >What do those compilers do for embedded objects? Presumably they always >state (this!=0) even if the embedded object is being created on the heap? >[IE, the (this==0) test, should your compiler decide to accept it, doesn't >really test if an object is on the stack vs heap or not, but rather whether >space has already been allocated for that object or not.] You are really making this more complicated than it is. The assign-to-this was a hack to allow constructors to do their own allocation. The technique was found to be unworkable in the presence of mulitple inheritance (and was ugly as sin anyway), so was declared obsolescent in favor of overloading new and delete. This nicely separates the orthogonal concerns of object initialization and space allocation. If a class C has one or more base classes, let's call C a complete object, and each of the base classes a sub-object. Data members of C are each complete objects, and each may in turn have sub-objects. If a constructor for C contains an assignment to "this" and is invoked as a result of using "new" to create a complete object of type C, then "this" will be zero on entry to C's constructor. In all other cases, "this" will be the address of the object (or sub-object) being constructed. Ordinarily, base classes are constructed prior to executing any of the user code in the derived class constructor. Continuing the above example (C::C() contains an assignment to "this"), a statement like C *cp = new C; means that C::C() is entered with this==0 and no base classes have been constructed -- and of course no space for the object has been allocated. Immediately following each assignment to "this" in C::C(), the compiler generates code to construct all of the base classes and perform all of the initializations in the constructor header. Such construction and initialization cannot be done sooner than assignment to "this", and must not be done later. This is why each possible execution path through C::C() must contain one and only one assignment to "this". -- Steve Clamage, TauMetric Corp, steve@taumet.com