Does the C++ compiler generate the hidden "this" pointer for all member methods, or only for those who reference members?
问题:
回答1:
Short answer: yes.
Longer answer: Well, if it's not using ANY member variables, why would it be a member function in the first place [and not a static member function]. (Yes, there may be cases where an interface provides a member method that isn't doing anything with any member content, since it's just doing something like printing an error message for calling this function on the wrong type, or it's a "we need this sometimes function", and in the cases when nothing needs to be done, it's an empty function).
Since we can use a member function without the compiler knowing what it actually does (for example in the case of different source files for the "use" and "definition" of the function), the compiler MUST follow the same calling convention for all calls, whether the this
pointer is actually needed or not. It's of course possible that if the code if visible to the compiler that it inlines the function or otherwise can make optimizations that produce better code under circumstances that allow this. But the "default" if the compiler doesn't know any better is to pass this
along to the function, whether it is actually needed or not.
回答2:
Quote from the C++ Standard (Draft N3242):
9.3.2 The this pointer
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.
I think this means that it is present in all member functions.
回答3:
"The C++ compiler" might act quite differently, depending on who he is at the exact point in space and time.
That said, the way most compilers implement classes and objects, this
is part of every instance of a class. This means, it is accessible in the complete scope of the object.
回答4:
Every object in C++ has access to its own address through a pointer called this pointer. The this
pointer is an implicit parameter to all member functions.Where as friend functions do not have a this
pointer. Only member functions have this
pointer.
回答5:
class Interval
{
public:
long GetTime()
{
//Code
}
void SetTime(long value)
{
//Code
}
}
Suppose you have written this code. Compiler will add the this pointer automatically. And it will appear to you when you view the compiler written code for your program.
Compiler will add as follows:
void Interval::SetTime(Interval* this, long value)