Showing posts with label this pointer. Show all posts
Showing posts with label this pointer. Show all posts

Tuesday, March 27, 2007

C++ : 'this' pointer representation

How is the 'this' pointer represented? The C++ standard states:

9.3.2/1

In the body of a nonstatic (9.3) member function, the keyword this is a non-lvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.

But, in many texts I have read that the 'this' pointer is considered a constant. So, I did what I usually do when faced with extreme difficulty, shoot a mail to Mr Stroustrup. Here's a part of conversation that followed:

Dear Mr Stroustrup,

I am sorry if I am disturbing you.
In the C++ standard following is stated for the 'this' pointer.

-----------
9.3.2/1

In the body of a nonstatic (9.3) member function, the keyword this is a non-lvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.
----------

While reading 'Inside the C++ Object model', by Mr Stanley Lippman, I came through 'this' being a constant pointer: myclass *const this, and const myclass *const this. And he writes that this technique was used in 'cfront'.

My point is, I always considered 'this' to being a constant pointer so that we can validate it being a non-LValue as the standard requires it to be. But if we stick to the standard then what Mr Lippman writes turns out to be non-standard. What should I assume? In the C++ community at Orkut, I replied with the following

and it must be

void zaman::shout (const zaman *const this, .....) const {}

and

void zaman::shout(zaman *const this, .....) {}


Waiting anxiously for reply

----------------------------

His reply:

The committee decided (to simplify overloading rules, I think) to express the fact that you cannot change the value of "this" as it being a non-lvalue. I originally expressed its immutability by saying that it was a *const. Undoubtedly, you can find some example where that difference matter, but you'll have to look hard and the likelihood of such an example appearing in real come must be minimal.

-------------------------------

So, it's not a constant pointer. -- Answer