问题描述
我正在阅读此问题的答案 C ++的优点和缺点/ a>,并在阅读评论时得到了这个疑问。
一些更进一步的论据为什么 this
作为参考是有意义的:
- 考虑
项目1
code>更有效的C ++ :当保证我们有一个有效的对象,即不是一个NULL(我的解释)使用引用。 - 此外,引用被认为比指针更安全(因为我们不能用一个离散指针来调整内存)。
- 第三,访问引用(
。
)的语法比访问指针(- >
或(*)
)。
当语言第一次演变时,在早期版本中,真实用户没有引用,只有指针。
的使用之一
是一个对象获取一个指向自身的指针。如果它是一个引用,我们必须写& this
。另一方面,当我们写一个赋值运算符时,我们必须 return * this
,它看起来比较简单 return this
。所以,如果你有一个空白的石板,你可以争论任何一种方式。但是C ++逐渐响应来自用户社区的反馈(像最成功的事情)。向后兼容性的价值完全压倒了源自这个
作为引用或指针的次要优点/缺点。
I was reading the answers to this question C++ pros and cons and got this doubt while reading the comments.
My question is, why this
is a pointer a not a reference? Any particular reason for making it a pointer?
Some further arguments why this
being a reference would make sense:
- Consider
Item 1
fromMore Effective C++
: use references when it is guaranteed that we have a valid object i.e. not a NULL (my interpretation). - Furthermore, references are considered safer than pointers (because we can't screw the memory up with a stray pointer).
- Thirdly, the syntax for accessing references (
.
) is a little bit nicer and shorter than accessing pointers (->
or(*)
).
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.
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.
这篇关于为什么'这是一个指针,而不是一个参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!