这不是一个真正的指针?

this is not a real pointer?

我正在阅读有关 virtual table 的内容。说到指针__vptr, 据说作者

Unlike the *this pointer, which is actually a function parameter used by the compiler to resolve self-references, *__vptr is a real pointer. Consequently, it makes each class object allocated bigger by the size of one pointer.

这里说this实际上是一个函数参数是什么意思?而this不是真正的指针吗?

这两个指针都是真实的,因为它们在内存中存储了其他东西的地址。 "real" 作者的意思是 "stored within the class",而不是 this 指针,它被传递给成员函数而不存储在对象本身中。本质上,指向 __vptr 的指针是对象的一部分,而 this 指针不是。

this 总是 一个隐藏的隐式 形式论证。实际上,class 的每个非 static 成员函数都得到一个隐含的第一个参数,即 this

所以在

class Foo {
  int x; // a field, i.e. an instance variable
  void bar(double x);
};

Foo::bar 函数有两个参数,就好像它是 C(不是 C++)函数一样

void Foo__bar(Foo* mythis, double x);

实际上,name mangling 编译器正在将第一个转换为与第二个非常接近的等价物。 (我使用 mythis 而不是 this 因为 this 是 C++ 中的关键字)。

原则上,ABI of your implementation could mandate a different passing convention for this (e.g. use another machine register) and for other explicit arguments. In practice, it often does not. On my Linux system the x86-64 ABI (its figure 3.4 page 21) defines a calling convention that passes this (and first pointer formal argument to C function) in %rdi processor register.

实际上,在 C++ 中,大多数(但不是全部)成员函数都很小(在 classinlined by the optimizing compiler (and the latest C++11 and C++14 standards have been written with optimizing compilers in mind; see also this 中定义)。在那种情况下,this 存储在哪里的问题实际上变得毫无意义......(因为内联)。

virtual method table (vtable) is generally an implicit first pointer field (or instance variable) of objects, but things could become more complex, e.g. with virtual multiple inheritance. the vtable data itself (the addresses of virtual functions) is generated by the compiler. See also this answer.

理论上,C++ 实现可以通过 vtable 之外的另一种机制提供 dynamic method dispatching。实际上,我知道没有 C++ 实现这样做。