成员函数如何传递"this"指针

How do member functions pass the "this" pointer

本文关键字:this 指针 何传递 函数 成员      更新时间:2023-10-16

假设我有一个类Foo,它有一个返回非常量引用的成员函数,它本身运行一个使用 const this指针的成员函数:

class Foo{
public:
    Foo& display(std::ostream& os) { do_display(os); return *this; }
private:
    void do_display(std::ostream& os) const { os << contents; }
    std::string contents;
}

display运行do_display时,this指针被隐式转换为指向 const 的指针。那么,为什么当do_display终止时,display仍然能够更改调用它的对象呢?据我所知,通常不可能将指向 const 的指针分配给指向非 const 的指针。任何见解都值得赞赏。

display 中转换非常量指针以将其传递给 do_display 会创建一个不同类型的新指针;它不会更改现有指针的类型。将this传递给成员函数与将参数传递给非成员函数非常相似:

// A non-const member function receives `this` as a non-const pointer
Foo& display(Foo * this, std::ostream & os) {
    // Pass a copy of `this`, converted to `Foo const *`
    do_display(this, os);
    // The local `this` is still `Foo *`
    return *this;
}
// A const member function receives `this` as a const pointer
void do_display(Foo const * this, std::ostream & os) {os << this->contents;}

在C++ const访问通常只是一个编译时属性 [1],引入该属性是为了简化对对象状态的控制。[2]

该方法do_display()不会更改任何this,但它在其范围内将访问限制为只读。调用返回的 do_display() 方法后,访问在 display() 方法的范围内像以前一样进行读写。


[1] 这就是选择抛弃 const 的原因,如果常量只是一个声明性,这可以被认为是安全的。

[2] 参见有效C++中的项目#3:改进程序和设计的55种特定方法(第3版):斯科特·迈耶斯或例如康斯特正确性 - C++教程 - Cprogramming.com