gpt4 book ai didi

c++ - 如果从构造函数/析构函数中不加限定地调用虚函数,是否会发生虚分派(dispatch)?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:37:09 24 4
gpt4 key购买 nike

struct A
{
virtual ~A() { f(); }

virtual void f() {}
};

我已将我的问题编辑得更具体..

在此代码示例中,调用 f() 可以使用虚拟分派(dispatch),还是保证等同于 A::f()

您能否提供 C++ 标准中的相关部分?谢谢。

最佳答案

在构造函数或析构函数中,子类对象要么尚未构造,要么已经被销毁。因此,虚拟分派(dispatch)不会导致使用派生类版本,而是调用基类版本。

根据标准,[class.cdtor]/4:

Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2). When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class’s non-static data members, and the object to which the call applies is the object (call it x) under construction or destruction, the function called is the final overrider in the constructor’s or destructor’s class and not the one overriding it in a more-derived class. If the virtual function call uses an explicit class member access (5.2.5) and the object expression refers to the complete object of x or one of that object’s base class subobjects but not x or one of its base class subobjects, the behavior is undefined.

举个例子:

struct V {
virtual void f();
virtual void g();
};
struct A : virtual V {
virtual void f();
};
struct B : virtual V {
virtual void g();
B(V*, A*);
};
struct D : A, B {
virtual void f();
virtual void g();
D() : B((A*)this, this) { }
};
B::B(V* v, A* a) {
f(); // calls V::f, not A::f
g(); // calls B::g, not D::g
v->g(); // v is base of B, the call is well-defined, calls B::g
a->f(); // undefined behavior, a’s type not a base of B
}

另请注意,如果调用的函数是纯虚拟函数,这可能是不安全的,来自 [class.abstract]/6:

Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined.

关于c++ - 如果从构造函数/析构函数中不加限定地调用虚函数,是否会发生虚分派(dispatch)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18456695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com