gpt4 book ai didi

c++ - 为什么 'this' 是指针而不是引用?

转载 作者:行者123 更新时间:2023-12-02 10:38:36 24 4
gpt4 key购买 nike

我正在阅读这个问题的答案 C++ pros and cons并在阅读评论时遇到了这个疑问。

programmers frequently find it confusing that "this" is a pointer but not a reference. another confusion is why "hello" is not of type std::string but evaluates to a char const* (pointer) (after array to pointer conversion) – Johannes Schaub - litb Dec 22 '08 at 1:56

That only shows that it doesn't use the same conventions as other (later) languages. – le dorfier Dec 22 '08 at 3:35

I'd call the "this" thing a pretty trivial issue though. And oops, thanks for catching a few errors in my examples of undefined behavior. :) Although I don't understand what info about size has to do with anything in the first one. A pointer is simply not allowed to point outside allocated memory – jalf Dec 22 '08 at 4:18

Is this a constant poiner? – yesraaj Dec 22 '08 at 6:35

this can be constant if the method is const int getFoo() const; <- in the scope of getFoo, "this" is constant, and is therefore readonly. This prevents bugs and provides some level of guarantee to the caller that the object won't change. – Doug T. Dec 22 '08 at 16:42

you can't reassign "this". i.e you cannot do "this = &other;", because this is an rvalue. but this is of type T*, not of type T const . i.e it's a non-constant pointer. if you are in a const method, then it's a pointer to const. T const . but the pointer itself is nonconst – Johannes Schaub - litb Dec 22 '08 at 17:53

think of "this" like this: #define this (this_ + 0) where the compiler creates "this_" as a pointer to the object and makes "this" a keyword. you can't assign "this" because (this_ + 0) is an rvalue. of course that's not how it is (there is no such macro), but it can help understand it – Johannes Schaub - litb Dec 22 '08 at 17:55


我的问题是,为什么是 this指针不是引用?使它成为指针的任何特殊原因?

一些进一步的论点为什么 this作为引用是有道理的:
  • 考虑Item 1来自 More Effective C++ :当保证我们有一个有效的对象时使用引用,即不是 NULL(我的解释)。
  • 此外,引用被认为比指针更安全(因为我们不能用杂散的指针搞砸内存)。
  • 第三,访问引用的语法( . )比访问指针( ->(*) )更好更短。
  • 最佳答案

    当语言第一次发展时,在真实用户的早期版本中,没有引用,只有指针。添加运算符重载时添加了引用,因为它需要引用才能始终如一地工作。
    this的用途之一是让对象获得指向自身的指针。如果它是一个引用,我们必须写 &this .另一方面,当我们编写赋值运算符时,我们必须 return *this ,它看起来更简单为 return this .所以如果你有一张白纸,你可以用任何一种方式争论。但是 C++ 逐渐演变为响应来自用户社区的反馈(就像大多数成功的事情一样)。向后兼容性的值(value)完全压倒了源自 this 的次要优势/劣势。作为引用或指针。

    关于c++ - 为什么 'this' 是指针而不是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57007481/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com