Is it possible to obtain the address of the 'this' pointer?
What is meant by "you cannot take the address of this
" is, that you cannot write &this
.
You are asking for the address represented by the this
pointer, right? This is, what your first output does.
this
itself is not materialized as a pointer, like e.g. MyString* x
would be. Here, x
itself has a location in memory and you can do sth. like &x
. This is not possible for this
.
The answer to your last question is: yes, this
is a keyword. The expression this
is a primary expression. You can read about it in Section [expr.prim.this]
of the C++ standard.
I'm wondering which may give the address of
this
? Or both are wrong?
Neither is the address of this
, because the C++ abstract machine doesn't define an address for it. this
is like 0
. You can't get the address of 0, it's not an entity with storage, just some value. So what does this do?
int const& i = 0;
It creates a temporary object, initializes it with 0, and then binds the reference to it. The same exact thing occurs in your code. You create references to different temporary objects that hold the value of this
.
this
is a keyword that stands for the address of the object that the member function is being executed for. The C++ abstract machine doesn't require it to occupy storage, so it's always (logically) just a plain value, like 0.
There's merit to not requiring this
to occupy storage. It allows C++ to be implemented over an ABI where this
is passed in a register (something that isn't addressable normally). If &this
had to be well-defined, i.e. if this
had to be addressable, it would preclude an implementation from using a register for passing the address. The C++ standard generally aims not to tie implementations up like that.