c++ - 有什么方法可以检测是否使用非虚基析构函数错误地删除了一个类?

标签 c++

众所周知的场景:

#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; 
}

此外,如果 AB 的大小相同,即使 Valgrind 也无法捕捉到这样的错误。

是否有某种工具可以至少为调试构建捕获此类错误,或者是否有某种习惯用法可以检测指定类的此类错误?

最佳答案

对于 gcc,您可以指定:

-Wdelete-non-virtual-dtor -Wsystem-headers

要查看 delete-non-virtual-dtorstd::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;

live

顺便说一句。您的示例类在基类中至少缺少一个虚函数。

[编辑]

将它变成错误使用:

 -Werror=delete-non-virtual-dtor -Wsystem-headers 

关于c++ - 有什么方法可以检测是否使用非虚基析构函数错误地删除了一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36248918/

相关文章:

c++ - 通过模板编译时父子关系

android - 在android上使用Qt蓝牙连接到arduino

c++ - BOOST_PP_VARIADIC_SIZE 未扩展

c++ - 从 Ethereum solidity 合约运行 C++ 脚本

c++ - 引用和对象切片

c++ - 完美转发可变参数模板到标准线程

c++ - volatile 结构与类型转换

c++ - RobuSTLy 找到 N 个直径相同的圆 : alternative to bruteforcing Hough transform threshold

c++ - opengl32.lib 如何在 Windows 上工作(仅 1.1 版)?它实际上实现了 OpenGL 功能吗?

c++ - 如果原始指针超出范围,智能指针是否保留分配的内存?