Calling class T's implementation of pure virtual from T constructor without qualification?

本小妞迷上赌 提交于 2020-01-04 05:28:20

问题


Considering that a virtual call of a T member function (directly or indirectly) from a constructor of a class T, can at most go down to T's implementation, does the following code, with unqualified call, have Undefined Behavior or not?

Note, to avoid noise: if you believe that member functions are not called virtually when invoked from a constructor, then please don't answer or comment here, but raise that issue in a separate SO question. Thank you.

struct Baze
{
    virtual void foo();
    virtual void bar() = 0;
    Baze(){ foo(); bar(); }
};

void Baze::foo() {}
void Baze::bar() {}

struct Derived: Baze
{
    void bar() override {}
};

int main()
{
    Derived{};
}

回答1:


I believe that this is covered by [class.abstract]/6 (N4140):

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.

So even though you have provided a definition for the pure virtual function, it's still technically UB.

There is a Core Working Group issue which addresses this here. It seems that the rules are unlikely to change to make this well-defined.



来源:https://stackoverflow.com/questions/42645853/calling-class-ts-implementation-of-pure-virtual-from-t-constructor-without-qual

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!