gpt4 book ai didi

c++ - 如果从析构函数调用纯虚函数是UB,为什么我们可以使用纯虚析构函数?

转载 作者:太空宇宙 更新时间:2023-11-04 11:32:24 27 4
gpt4 key购买 nike

众所周知,我们可以使用纯虚析构函数,如下所示:

struct A {
virtual ~A() = 0;
};
A::~A() {}

struct B : A {};

因为标准在 10.4 [class.abstract] p2

中说

A pure virtual function need be defined only if called ... with (12.4 [class.dtor])

之后在 12.4 [class.dtor] p9

A destructor can be declared virtual (10.3) or pure virtual (10.4); if any objects of that class or any derived class are created in the program, the destructor shall be defined.

这意味着上面的代码是完全有效的 - A::~A 可能是纯虚拟的,它被定义,B::~B 隐式调用 A::~A.

到目前为止,还不错。
然后我阅读了 10.4 [class.abstract] p6:

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.

但这正是我们在这里所做的 - 我们从析构函数中调用纯虚函数 A::~A

那么,是不是存在某种矛盾?

最佳答案

没有收缩。

你调用了A的虚析构函数来自 B 的析构函数. A析构函数不是 B 的成员.

标准 § 9.3

成员函数

Functions declared in the definition of a class, excluding those declared with a friend specifier ( 11.3 ), are called member functions of that class

标准规定,当从抽象类析构函数/构造函数(在您的情况下,将是类 A )对其自身的纯函数之一进行虚拟调用时,存在未定义的行为虚拟成员函数。

[...] Member functions can be called from a constructor (or destructor) of an abstract class [...];

你对析构函数的引用是这样的:

  1. 您可以从抽象类的析构函数中调用成员函数
  2. 如果您同一抽象类的析构函数调用纯虚方法(通过虚调用),则存在未定义的行为。

关于c++ - 如果从析构函数调用纯虚函数是UB,为什么我们可以使用纯虚析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24229131/

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