Bad Uses of the this Pointer

The this pointer is a const pointer, so a member function cannot change the pointer's value to make it point to something else. In early versions of C++, the this pointer was not a const pointer. This allowed a programmer to make assignments to the this pointer in order to perform customized memory allocation. For example:

// BAD TECHNIQUE: assignment to this

class foo

{

public:

foo() { this = my_alloc( sizeof( foo ) ); }

~foo() { my_dealloc( this ); this = 0; }

};

This type of special processing is not allowed in the current version of C++. If you need customized memory allocation, you can write your own versions of new and delete. See the section “Class-Specific new and delete Operators”.

Early versions of C++ also let you examine the this pointer to distinguish between objects allocated on the stack and those allocated with the free store. On entry to a constructor, the this pointer had a value of 0 if the constructor was being called for an object allocated with new, and had a nonzero value otherwise. This allowed you to perform different processing for dynamically allocated objects. This behavior is not supported in the current version of C++.