2

Could anyone tell me if the pointer "this" in object of class occupy memory when it was created?

class Temp {
private:
    Temp &operator=(const Temp &t) { return *this; }
}
yangxiao
  • 23
  • 3
  • Please use more words to explain what you are asking. What would an answer "Yes" mean to you? What if "No"? – Yunnosch Aug 27 '20 at 07:26
  • Not so sure what you are asking, but maybe this is so closely related that it helps: https://stackoverflow.com/questions/63557630/why-the-size-of-class-remains-same-on-adding-more-than-one-virtual-function/63557717#63557717 – Yunnosch Aug 27 '20 at 07:28
  • `this` is a keyword and doesn't consume any size at runtime. `this` results in a class pointer which has the usual pointer size. `this` accesses the argument of function/operator call which was implicitly given for the instance (the one which is left of `->`/`.` in the member call expression) and it may or may not be stored on stack, or may be stored in a register. `*this` results in a reference of the class. That instance occupies the size and storage according to where it has been allocated. – Scheff's Cat Aug 27 '20 at 07:39
  • @ Yunnosch: Haha, my question is really not detailed enough, thank you for your criticism. I will make improvements in the next question – yangxiao Aug 27 '20 at 08:12
  • @ Scheff: Thanks for your answer, this answer is very helpful to me. I think I may now understand how `this` works. – yangxiao Aug 27 '20 at 08:17

2 Answers2

6

this is the address of the object whose member function is being called, and it doesn't need to be stored anywhere.
It is usually implemented by passing its value as a "hidden" argument to the member functions, so it occupies memory in the same way as any other function argument occupies memory.

The "object-oriented" code

struct A
{
    int f() { return this->x; }
    int x;
};

int g()
{
    A a;
    return a.f();
}

will usually be implemented like this "non-object-oriented" code:

struct A
{
    int x;
};

int Af(A* self)
{
    return self->x;
}

int g()
{
    A a;
    return Af(&a);
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • Thank you for your answer sincerely! I think this answer gives me a deeper understanding of this pointer. – yangxiao Aug 27 '20 at 08:01
0

No, "this" is already by itself a memory reference and hence it would not occupy more memory than the object already does.