this is not a real pointer?

2020-04-09 19:51发布

I am reading something about virtual table. When it comes to pointer __vptr, it is stated that by the author

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.

What does it mean here by saying this is actually a function parameter? And this is not a real pointer?

2条回答
叛逆
2楼-- · 2020-04-09 20:44

Both pointers are real in the sense that they store an address of something else in memory. By "real" the author means "stored within the class", as opposed to this pointer, which is passed to member functions without being stored in the object itself. Essentially, the pointer to __vptr is part of the object, while this pointer is not.

查看更多
对你真心纯属浪费
3楼-- · 2020-04-09 20:50

this is always a hidden implicit formal argument. Practically speaking, every non static member function of a class is getting an implicit first argument which is this

so in

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

the Foo::bar function has two arguments, exactly as if it was the C (not C++) function

void Foo__bar(Foo* mythis, double x);

And actually, name mangling and the compiler is transforming the first into a very close equivalent of the second. (I am using mythis instead of this because this is a keyword in C++).

In principle, the 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.

Practically speaking, in C++, most -but not all- member functions are small (defined inside the class) and inlined by the optimizing compiler (and the latest C++11 and C++14 standards have been written with optimizing compilers in mind; see also this). In that case, the question of where is this stored becomes practically meaningless... (because of the inlining).

The 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.

In theory, a C++ implementation could provide the dynamic method dispatching by another mechanism than vtable. In practice, I know no C++ implementation doing that.

查看更多
登录 后发表回答