-->

Calling class T's implementation of pure virtu

2019-07-09 06:52发布

问题:

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.