Let's take this simple c++ program as an example:
#include <vector>
class A
{
void fun() { a = this + 1; }
A* a;
};
main()
{
std::vector<A> vec;
vec.resize(100);
}
Forgetting for the moment that this
is a pointer to some instantiation of A
, this question is about the variable this
itself, and where its contents (the value of the memory address) is stored.
It can't be a literal because the compiler can't know the location of class A
, so its contents must be allocated somewhere on the stack or heap as a variable. In this case the instances of A
are allocated on the heap; does this mean the this
pointer is also on the heap?
Looking at the resize
call of vec
, a compiler might do something like this under the hood:
std::vector<A>::resize(this, 100); // where 'this' is a pointer to vec
So my question is, where does the this
pointer come from? Ie. where is the contents of this
(the 32/64-bit memory address value) stored in memory for it to be passed to this method?
I would presume it can't be a normal member; so my first thought was that it's a mangled global variable of some sort, but then by storing an unknown number of them in a vector I don't see how the compiler could achieve this either. Where is the contentx of the this
variable stored in relation to the contents of the A
class member to which it refers?
If the standard has something to say about this, I would prefer an answer with reference to the standard.
Note that the reason I want to know is because I am concerned about false sharing of the memory allocated for the this
object if I modify member variables. Knowledge of where the this
object is stored might affect padding decisions.
this
.