且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么“this"是指针而不是引用?

更新时间:2022-11-01 16:30:46

当语言第一次发展时,在有真实用户的早期版本中,没有引用,只有指针.添加运算符重载时添加了引用,因为它需要引用一致地工作.

When the language was first evolving, in early releases with real users, there were no references, only pointers. References were added when operator overloading was added, as it requires references to work consistently.

this 的一个用途是让对象获得指向自身的指针.如果是引用,我们就必须写&this.另一方面,当我们编写赋值运算符时,我们必须return *this,这看起来比return this 更简单.所以如果你有一张白纸,你可以用任何一种方式争论它.但是 C++ 是为了响应用户社区的反馈而逐渐发展的(就像大多数成功的东西一样).向后兼容的价值完全压倒了由于 this 作为引用或指针而产生的次要优点/缺点.

One of the uses of this is for an object to get a pointer to itself. If it was a reference, we'd have to write &this. On the other hand, when we write an assignment operator we have to return *this, which would look simpler as return this. So if you had a blank slate, you could argue it either way. But C++ evolved gradually in response to feedback from a community of users (like most successful things). The value of backward compatibility totally overwhelms the minor advantages/disadvantages stemming from this being a reference or a pointer.