众所周知的场景:
#include <memory>
class A{};
class B : public A {};
int main()
{
std::unique_ptr<A> a = std::make_unique<B>();
// bam, when a gets deleted, we have undefined behavior.
return 0;
}
此外,如果 A
和 B
的大小相同,即使 Valgrind 也无法捕捉到这样的错误。
是否有某种工具可以至少为调试构建捕获此类错误,或者是否有某种习惯用法可以检测指定类的此类错误?
最佳答案
对于 gcc,您可以指定:
-Wdelete-non-virtual-dtor -Wsystem-headers
要查看 delete-non-virtual-dtor
由 std::default_delete
生成的警告,它将如下所示:
/usr/local/include/c++/5.3.0/bits/unique_ptr.h:76:2: warning: deleting object of polymorphic class type 'B' which has non-virtual destructor might cause undefined behaviour [-Wdelete-non-virtual-dtor] delete __ptr;
顺便说一句。您的示例类在基类中至少缺少一个虚函数。
[编辑]
将它变成错误使用:
-Werror=delete-non-virtual-dtor -Wsystem-headers
关于c++ - 有什么方法可以检测是否使用非虚基析构函数错误地删除了一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36248918/