问题
Ok, this is a very basic question.
What is the true reason why I can use the this pointer in c++ methods / member functions?
In other words: when I have
class foo
{
void bar();
}
Why can I use
void foo::bar()
{
this->...
}
I can imagine two possibilities:
- Is it some sort of automatically created member variable
- It is passed to each method as parameter (and thus each method is automatically extended by that parameter)
回答1:
As pointed out by several others, the this
keyword is often implemented by the compiler by passing it along as the first parameter to a member function, so that a member function: void SomeClass::func(int a, int b)
could internally look like: void SomeClass::func(SomeClass* this, int a, int b)
, and the const version like this: void SomeClass::func(const SomeClass* this, int a, int b)
.
However what I find most interesting about this, is that it is something that is not enforced by the standard.
The C++ standard says (§ 9.3.2 ad 1):
In the body of a non-static (9.3) member function, the keyword this is a prvalue 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
isX*
. If the member function is declared const, the type of this isconst X*
, if the member function is declared volatile, the type of this isvolatile X*
, and if the member function is declared const volatile, the type of this isconst volatile X*
. [ Note: thus in a const member function, the object for which the function is called is accessed through a const access path. —end note ]
This is interesting, because like with many other things, the C++ ABI is left mostly to the compiler, which can be troublesome. So while it is certainly true for most compilers (might even be all), that this
is implemented by being implicitly passed as the first parameter, it is not guaranteed by the standard, so it could be implemented differently by a new compiler, though I doubt it will happen.
回答2:
When a member function is invoked on a class member, C++ uses the keyword this
to refer to something that acts like an unmodifiable pointer to the class instance the function was invoked on. It behaves as if it was a parameter to the function.
You can think of foo.bar(1);
as kind of like bar(&foo, 1);
.
And you can think ofint foo::f(int);
as kind of like int f(foo const* this, int);
.
回答3:
If you look the assembly code of a class function you will notice that a hidden parameter is passed. This parameter is called the this pointer and is nothing more than the address of the current object. If this address was not passed then your compiler would have no idea what object to call. Another usage is to return a current object address which is extremely usefull in operator overloading for subsequent operations(assignment especially).
来源:https://stackoverflow.com/questions/33477090/why-can-i-use-this-in-methods