Path: utzoo!attcan!uunet!microsoft!jimad From: jimad@microsoft.UUCP (Jim ADCOCK) Newsgroups: comp.lang.c++ Subject: Re: testing this==0 Keywords: this Message-ID: <55488@microsoft.UUCP> Date: 27 Jun 90 17:59:00 GMT References: <1990Jun26.175953.16763@uncecs.edu> Reply-To: jimad@microsoft.UUCP (Jim ADCOCK) Distribution: comp Organization: Microsoft Corp., Redmond WA Lines: 38 In article <1990Jun26.175953.16763@uncecs.edu> harris@uncecs.edu (Mark Harris) writes: > >Help! I'm fairly new to C++, and I'm running into unexpected >behavior from my new Borland compiler. I thought that the value >of 'this' was supposed to be zero at the start of an object's >constructor if the object is being created on the heap. While the (this==0) test in mentioned in passing in Stroustrup's 1986 text, I believe it should be considered part of the assignment-to-this anachronism. In fact, even the compilers I have seen that support the assignment-to-this anachronism don't support the (this==0) test for objects on the heap. Only the very first C++ compiler I tried some years ago ever actually support the (this==0) test. The present definition on how things are suppose to work is as follows: a) don't assign to this, if you need to modify memory allocation behavior, overload operator new. b) if operator new ever returns zero, it is guaranteed that initialization will not be performed -- the constructor body will not even be executed, so in the following constructor: class mything { public: mything() { if (this==0) printf("Non-conforming compiler!\n"); } }; the printf should never occur, even if operator new fails to successfully allocate memory. [see E&S for the detailss] So the question becomes: is there a standard, portable way to test whether allocation is being done on the stack, heap, or wherever? Answer: nope! There are lots of non-standard, non-portable ways to test this, however. Possibly the most portable thing to do is to test if this is in a region reasonably considered stack, since stack is typically contiguous [heap need not be.] Could still cause you troubles in a lightweight threaded application, however.