gpt4 book ai didi

c++ - 编译器真的强制执行纯虚拟析构函数吗?

转载 作者:太空狗 更新时间:2023-10-29 23:35:09 26 4
gpt4 key购买 nike

为了验证声明“编译器和链接器强制存在纯虚拟析构函数的函数体。”来自 geeksforgeeks article ,我编译了这段代码:

class Base
{
public:
virtual ~Base()=0; // Pure virtual destructor
};

class Derived : public Base
{
public:
~Derived()
{
std::cout << "~Derived() is executed";
}
};

int main()
{
//Derived d; <<<
return 0;
}

编译没有任何错误。那么为什么在这种情况下编译器没有选择强制函数体的存在呢?

最佳答案

因为如果您执行 ODR1 违规,编译器(实际上是整个翻译过程)没有强制执行任何操作。根据 [basic.def.odr/4] 处的 C++ 标准:

Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required. The definition can appear explicitly in the program, it can be found in the standard or a user-defined library, or (when appropriate) it is implicitly defined (see [class.ctor], [class.dtor] and [class.copy]). An inline function shall be defined in every translation unit in which it is odr-used.

编译器完全有权判断您的程序实际上没有使用2 Derived 的析构函数(因此是 Base 的析构函数),只是懒得通知你。


<子>1 一个一个定义定义规则规则
2 What does it mean to “ODR-use” something?

关于c++ - 编译器真的强制执行纯虚拟析构函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45975114/

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