'this' 在 C++ 中是指向引用的指针?

'this' in C++ is a pointer to a reference?

我知道这很愚蠢,标题可能不是答案.. 我一直认为 this 是指向当前 object 的指针,它在 object(不是静态方法)

的每个方法调用中提供

但是看看我的代码实际上 return 例如:

Test& Test::func () 
{ 
   // Some processing 
   return *this; 
} 

this 的解引用是 returned... 而 return 类型是对 object... 的引用,那是什么意思this?幕后有什么我不太了解的地方吗?

请记住,引用只是对象的一个不同的名称

这意味着返回引用与返回类型抽象级别的对象是一回事;结果中 不同:返回引用意味着调用者获得了对 current 对象的引用,而返回一个对象给了他(引用)当前对象的 copy - 具有所有后果,例如调用复制构造函数,做出深层复制决策等。

来自 cppreference

The keyword this is a prvalue expression whose value is the address of the object, on which the member function is being called.

然后(可能更容易掌握):

The type of this in a member function of class X is X* (pointer to X). If the member function is cv-qualified, the type of this is cv X* (pointer to identically cv-qualified X). Since constructors and destructors cannot be cv-qualified, the type of this in them is always X*, even when constructing or destroying a const object.

所以,this不是指向引用的指针,而只是一个指针。

实际上你不能有一个指向引用的指针,因为获取引用的地址会得到引用对象的地址。

此外,C++中没有特殊的语法来形成引用。相反,必须在初始化时绑定引用,例如:

int x = 3;
int& y = x;   // x is int, but y is int&
assert( &y == &x); // address of y is the address of x

从函数返回引用时类似:

int& get_x() {
    static int x = 3;
    return x;
}

简单来说:

test t1;  //  t1 is a test object.

test& t2 = t1; //  t2 is another name for t1.

test* t3; //  t3 holds an address of a test object.

*t3; //  derefernce t. which gives you, the test object that t3 points to.

this是指向当前测试对象的指针。
因此 *this 是当前测试对象,并且因为 return 值类型是 test&,当您调用该函数时,您将获得与调用该函数相同的对象。