Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

c++ - Where is the 'this' pointer stored in computer memory?

Where exactly is the 'this' pointer stored in memory? Is it allocated on the stack, in the heap, or in the data segment?

#include <iostream>
using namespace std;

class ClassA
{
    int a, b;

    public:
        void add()
        {
            a = 10;
            b = 20;
            cout << a << b << endl;
        }
};

int main()
{
    ClassA obj;
    obj.add();
    return 0;
}

In the above code I am calling the member function add() and the receiver object is passed implicitly as the 'this' pointer. Where is this stored in memory?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...