使用“this”指针占用内存

yan*_*iao 2 c++ memory pointers class

谁能告诉我类对象中的指针“this”在创建时是否占用内存?

class Temp {
private:
    Temp &operator=(const Temp &t) { return *this; }
}
Run Code Online (Sandbox Code Playgroud)

mol*_*ilo 6

this是调用其成员函数的对象的地址,不需要存储在任何地方。
它通常通过将其值作为“隐藏”参数传递给成员函数来实现,因此它占用内存的方式与任何其他函数参数占用内存的方式相同。

“面向对象”代码

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

int g()
{
    A a;
    return a.f();
}
Run Code Online (Sandbox Code Playgroud)

通常会像这个“非面向对象”代码一样实现:

struct A
{
    int x;
};

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

int g()
{
    A a;
    return Af(&a);
}
Run Code Online (Sandbox Code Playgroud)