solomon@crystal.UUCP (Marvin Solomon) (03/28/86)
I've been bitten by a couple of passages in the C++ book that are at best ambiguities and at worst mistakes. The first example is the first sentence of section 5.5.7, p. 164: "When assigning to 'this' in a constructor, the value of 'this' is undefined until that assignment". A grammatical purist will note that "assigning" in this sentence is a dangling participle: Who is doing the assigning? If a contstuctor does NOT contain an explicit assignment to 'this', the compiler inserts at the top of the constructor a statement to the effect of if (this==0) this = (thistype *) new char[thissize]; If an explicit assignment to 'this' appears ANYWHERE IN THE BODY OF THE CONSTRUCTOR, the default initialization is omitted. In that case, the initial value of 'this' is zero for free-storage objects (created by 'new'), and points to an existing object otherwise. For example, obj x(10,20); will allocate sizeof(obj) bytes on the stack and then call obj's constructor with 'this' pointing to the space. All of this is described fairly clearly in the following paragraph in the book. What the quoted sentence is really trying to say is that any constructor that assigns to 'this' had better ensures that 'this' is non-zero before it attempts to access any member variables. It is not the value of 'this' that is undefined; rather, the locations of member variables are undefined when 'this'==0. The second example may well be a bug in the implementation (version 1.0) rather than the book, but I'm not sure. In section r7.2.4, p. 259, we find, "However, deleting a pointer with the value zero is harmless." I guess it all depends on what you mean by "harmless". If the class has a destructor, that destructor is called, even if the pointer is null. Thus a destructor had better check that this!=0 before attempting to access member variables. I would argue that this a "feature" rather than a "bug", since the destructor is really an attribute of the class rather than the particular object. There may be applications that wish to give some specific meaning to 'delete 0'. Note that the same sort of thing happens with other member functions: p->f() is well defined, even if p==0. This can be useful. For example class list { int car; list *cdr; public: print() { if (this==0) cout<<"nil"; else { cout<<car<<"."; cdr->print(); } } } -- Marvin Solomon Computer Sciences Department University of Wisconsin, Madison WI solomon@uwisc ...{ihnp4,seismo,allegra}!uwvax!solomon