c++中的指针"this"支持虚机制吗?

does pointer "this" in c++ support virtual mechanism?

考虑一下:

class B {
    void f() { vf(); };
    virtual void vf();
};

class D: public B{
    virtual void vf();
};

我认为在 C++ 中 B::f() 的实现是这样的:

f(B *this) {
    *(this->vptr[index])(this);
}

下面的例子中D::vf()是通过虚拟机制调用的吗?

B *p = new D();
p->f(); 

对于给定的示例,答案是肯定的,但对于来自基础 class 的构造函数的调用则不是,它在派生的 class 被构造之前执行。

稍微修改一下示例:

#include <iostream>

class B {
public:
    B() { f(); }

    void f() { vf(); };
    virtual void vf()  { std::cout << "B::vf" << std::endl; }
};

class D: public B{
    void vf() override { std::cout << "D::vf" << std::endl; }
};

int main()
{
    B *p = new D();  // calls D::D() --> B::B() --> B::f() --> B::vf()
    p->f();          // calls B::f() --> D:vf()
}

输出为:

B::vf
D::vf

I thought that in C++ the implementation of B::f() is something like that:

f(B *this) {
    *(this->vptr[index])(this);
}

index 的值在编译时总是已知的。 vtable 是一个“记录”(一种结构,如 C/C++ struct)而不是数组或“table”。所以就像:

void f(B *This) {
    (This->vptr.ptr_f)(This);
}

注意:您不需要在 C 或 C++ 中取消引用指向函数的指针。

Is D::vf() called through the virtual mechanism in the following example?

B *p = new D();
p->f();

这取决于编译器及其“智能”。在低优化级别,它将通过虚拟机制(又名动态调度)。

使用高效的优化器,可以确定所使用对象的真实类型(此处D),并且可以避免动态调度。