让我们举个例子:
/* Source.cpp */
struct Base {
virtual void func() = 0;
};
struct Derived : public Base {
virtual void func() override { }
};
int main() {
return 0;
}
在通过g++ Source.cpp -Wnon-virtual-dtor
进行编译(在g ++ 8.3.0上)时,我们得到了:
Source.cpp:2:8: warning: 'struct Base' has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]
struct Base {
^~~~
Source.cpp:6:8: warning: base class 'struct Base' has accessible non-virtual destructor [-Wnon-virtual-dtor]
struct Derived : public Base {
^~~~~~~
Source.cpp:6:8: warning: 'struct Derived' has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]
要做的实用是什么?
virtual ~Base() = default;
添加到每个此类Base
中以消除警告(不利的是,我们正在添加样板代码,该代码本来就似乎什么也没做)。-Wnon-virtual-dtor
并保持代码不变? (缺点是我们可能允许内存泄漏,还是我们)