Where is the ‘this’ pointer stored in computer memory?

The easiest way is to think of this as being a hidden extra argument that is always passed automatically.

So, a fictional method like:

size_t String::length(void) const
{
  return strlen(m_string);
}

is actually more like this under the hood:

size_t String__length(const String *this)
{
  return strlen(this->m_string);
}

and a call like:

{
  String example("hello");
  cout << example.length();
}

becomes something like:

cout << String__length(&example);

Note that the above transformation is simplified, hopefully to make my point a bit clearer. No need to fill up the comments with “whaaa, where’s the marshalling for method overloading, huh?”-type objection, please. 🙂

That transforms the question into “where are arguments stored?”, and the answer is of course “it depends”. 🙂

It’s often on the stack, but it could be in registers too, or any other mechanism that the compiler considers is good for the target architecture.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)