Path: utzoo!utgpu!watserv1!watmath!att!att!dptg!ulysses!andante!alice!ark From: ark@alice.att.com (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: operator++() and testing 'this' Message-ID: <11489@alice.att.com> Date: 15 Oct 90 04:25:45 GMT References: <1990Oct14.224706.1934@nowhere.uucp> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 57 In article <1990Oct14.224706.1934@nowhere.uucp>, sking@nowhere.uucp (Steven King) writes: > > In article <1990Oct9.144542.19983@sco.COM> jfischer@sco.COM (Jonathan A. Fischer) writes: > >>Can one rely on 'this' having the value zero on entry to the constructor > >>if the object is allocated on the free store? > > Yep, according to the same anachronisms section. Not quite. First, I should point out that everything I am about to describe is an anachronism. You shouldn't use this stuff. I'm only describing it to make it easier for you to understand existing programs that do use it. It will go away in time. You will see why when you see how scruffy it is. A constructor has different semantics depending on whether or not it contains an ASSIGNMENT to `this.' Here, `contains' means `textually contains' -- that is, an actual assignment expression with `this' as its left-hand side. If a constructor doesn't assign to `this,' then the value of `this' at entry to the constructor is the value of the object being constructed, period. This is true whether or not the object is allocated on the free store. Thus, for example: struct A { A() { printf("%lx\n", (long) this); } }; will print a nonzero value every time an A object is created, regardless of whether it is an automatic variable, a static variable, or on the free store. If a constructor DOES assign to `this,' then the value of `this' may or may not be zero at entry. If the value of `this' is zero, it means that the object is being allocated on the free store AND is not part of a larger object. In that case it is the constructor's responsibility to allocate an appropriate amount of memory and assign it to `this.' If the value of `this' at entry is nonzero, then memory has already been allocated for the object. Nevertheless, the constructor is expected to assign a value to `this' ANYWAY -- the act of doing so causes the base class(es) to be constructed and the initializers to be executed. In other words, a constructor that assigns to `this' must do so in every path through that constructor. That means it is usually necessary to say `this = this;' somewhere, because if memory has already been allocated then it is impossible to reallocate it somewhere else (think of the case where the object is part of a larger object that has already been partly constructed). Do you see why this usage has been deprecated? -- --Andrew Koenig ark@europa.att.com