this is not a real pointer?

后端 未结 2 805
独厮守ぢ
独厮守ぢ 2021-01-19 21:38

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

Unlike the *this

相关标签:
2条回答
  • 2021-01-19 22:18

    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.

    0 讨论(0)
  • 2021-01-19 22:18

    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.

    0 讨论(0)
提交回复
热议问题