从T构造函数中调用类T的纯虚函数的实现而没有资格吗? [英] Calling class T's implementation of pure virtual from T constructor without qualification?

查看:93
本文介绍了从T构造函数中调用类T的纯虚函数的实现而没有资格吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到 T T 成员函数的虚拟调用(直接或间接) >,最多只能归结为 T 的实现,下面的代码是否带有不合格的调用,是否具有未定义的行为?

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?

注意,为避免噪音:如果您认为从构造函数中调用时实际上并未调用成员函数,那么请不要在此处回答或评论,而应在一个单独的SO问题。谢谢。

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{};
}


推荐答案

我相信已涵盖通过 [class.abstract] / 6 (N4140):

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


成员函数可以从抽象类的构造函数(或析构函数)中调用;对于从这样的构造函数(或析构函数)创建(或销毁)
的对象直接或间接地对纯虚函数进行
虚拟调用(10.3)的效​​果是不确定的。

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.

因此,即使您已经提供了纯虚函数的定义,但从技术上讲它仍然是UB。

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.

这篇关于从T构造函数中调用类T的纯虚函数的实现而没有资格吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆