Does the C++ compiler generate the hidden "this" pointer for all member methods, or only for those who reference members?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Do the Java Integer and Double objects have unnece
- Why does const allow implicit conversion of refere
- thread_local variables initialization
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Quote from the C++ Standard (Draft N3242):
I think this means that it is present in all member functions.
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:
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 athis
pointer. Only member functions havethis
pointer."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.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 passthis
along to the function, whether it is actually needed or not.