成员函数如何传递"this"指针
How do member functions pass the "this" pointer
假设我有一个类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
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 关于C++中具有多重继承"this"指针的说明
- Doees the 'this' 指针参与虚函数的多态行为
- 为什么成员函数内的"this"指针为空?
- "this"指针的值在对象的生存期内是否恒定?
- 如何将'this'指针传递给C++ WinAPI 线程?
- 无法"this"指针传递到另一个类并在 CPP 中调用该类的任何方法
- 'this'指针是否可以在 c++ 标头声明中使用?
- 为什么在通过引用返回运算符分配时取消引用'this'指针?
- 在类方法中使用 "this" 指针是否是一种好的做法?
- 为什么直接传递"this"指针来存档是一个错误,而另一个相同类型的指针是可以的?
- C++虚拟方法,不需要"this"指针 - 优化
- 指向成员函数签名的指针中缺少"this"指针
- 是否可以获取'this'指针的地址?
- 静态类成员不是与 this 指针没有关联吗?
- 为什么有必要将"this"指针作为"arg"参数传递给pthread_create
- 编译错误:2 个重载没有'this'指针的合法转换。使用结构
- 对象的"this"指针是否等于指向其(单个)基类的指针?
- Do=在lambda的捕获列表中捕获this指针
- 将"this"指针传递给析构函数中的其他类/函数