c++ - &**this 究竟返回了什么?

标签 c++ pointers

这是一个指向调用对象的指针(它返回右值)。

*这是一个指向调用对象指针的指针(它返回地址的值)。

**这是一个指向调用对象(???)的指针的指针。

&***这是对调用对象指针(???)的指针的引用。

std::vector<int>:: iterator i = vector1.begin();

i 是指向它自己的右值的指针(返回它自己的值)。

*i 是 vector 中包含的对象的右值指针(返回 &value 中指向的值)。

**i 是指向 vector 中包含的对象的右值指针的指针 (???)。

我真的很困惑。

这是一个示例代码,我们在其中找到表达式 &**this:

class _Iter
{
private:
    ListElem *pCurr;
    const List *pList;

public:
    _Iter(ListElem *pCurr, const List *list)
        : pCurr_(pCurr), pList(list)
    {}

    T& operator*() { return pCurr_->data; }
    T* operator->() { return &**this; }
};

最佳答案

this 是指向当前对象的指针。

*this 是对当前对象的引用,即 this 取消引用。

**this 是在当前对象上调用的重载一元 operator* 函数的返回值。

如果从 **this 返回的对象有一个重载的 operator&() 函数,那么 &**this 计算返回值(**this).operator&() 的。否则,&**this 是指向在当前对象上调用的重载一元 operator* 函数的返回值的指针。

例子:

#include <iostream>

struct A
{
   int b;
   int a;
   int& operator*() {return a;}

   int* test()
   {
      return &**this;
   }
};

int main()
{
   A a;
   std::cout << "Address of a.a: " << a.test() << std::endl;
   std::cout << "Address of a.a: " << &(*a) << std::endl;
   std::cout << "Address of a.a: " << &(a.a) << std::endl;
   return 0;
}

示例输出:

Address of a.a: 0x7fffbc200754
Address of a.a: 0x7fffbc200754
Address of a.a: 0x7fffbc200754

关于c++ - &**this 究竟返回了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22368300/

相关文章:

c++ - Spritebatch 只绘制第一个 Sprite

c++ - _WIN32_WINNT 宏,适用于 win7 和 winxp

c++ - 对象上的范围解析运算符

c++ - 为什么指针数组会在函数完成时自行初始化?

c++ - 将自定义数组传递给函数的问题 (c++)

c - 指针重定义错误

c++ - 指针解引用是原子的吗?

c++ - 仅在函数中设置静态变量一次

c - C 中被调用函数的返回值

c - 获取一个子程序以在 C 中返回三个独立的随机数数组