gpt4 book ai didi

c++ - 禁止从构造函数调用纯虚方法的编译器选项

转载 作者:行者123 更新时间:2023-11-27 23:56:17 25 4
gpt4 key购买 nike

关于这个问题,How to resolve "pure virtual method called"是否有一个编译器选项,当从构造函数/析构函数调用虚方法时会引发错误?当存在纯虚方法时,程序会在运行时因段错误而崩溃。

多次证明这是一个糟糕的设计:

When you call virtual methods from within your constructors/destructors it's not the overriden versions of them that are called.

编辑:

我专门针对 MSVC 询问,但如果每个编译器(GCC、CLANG 等)都有一个选项,这将很有用。

最佳答案

is there a compiler option that raises error when a virtual method is called from constructor/destructor? When there is a pure virtual method, the program will crash at runtime with segmentation fault.

but it would be useful if there is an option for each compiler (GCC, CLANG, etc).

对于 GCC 和 Clang,选项是 -Werror。这将导致所有警告引发错误。如果在构造函数或析构函数中直接调用纯虚函数,两个编译器都会默认发出警告。

如果调用非纯虚函数,当然不会有警告/错误。它具有明确定义的行为。此外,编译器通常无法检测到对纯虚函数的间接调用。

我不知道 MSVC。

This is proven many times to be a bad design:

如果您指的是在 ctor./dtor. 中虚拟调用纯虚函数,那么糟糕的设计是一种轻描淡写的说法。行为未定义。如果运气不好,程序甚至可能不会崩溃。

关于c++ - 禁止从构造函数调用纯虚方法的编译器选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42644883/

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