I read that this
is an rvalue and we cannot get its address by applying &this
.
In my code, I have tried to use a reference binding to this
. I'm wondering which way will give the address of this
? Or are both wrong?
What exactly is this
? An lvalue, an rvalue, a keyword, or something else?
void MyString::test_this() const{
std::cout << "this: " << this << std::endl;
const MyString * const& this_ref = this;
std::cout << "thie_ref: " << &this_ref << std::endl;
const MyString * const&& this_right = this;
std::cout << "thie_right: " << &this_right << std::endl;
}
//this: 00CFFC14
//thie_ref: 00CFFB14
//thie_right: 00CFFAFC
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.