$ valgrind --leak-check=yes ./a.out ==10533== HEAP SUMMARY: ==10533== in use at exit: 0 bytes in 0 blocks ==10533== total heap usage: 5 allocs, 6 frees, 74,344 bytes allocated ==10533== ==10533== All heap blocks were freed -- no leaks are possible ==10533== ==10533== For counts of detected and suppressed errors, rerun with: -v ==10533== ERROR SUMMARY: 1 errors from 1contexts (suppressed: 0 from 0)
出现这个问题的根本原因是 q.push(t), 当我们查看std::queue::push方法时,我们看到添加到队列的元素”初始化为 x 的副本”。它实际上是一个全新的对象,它使用复制构造函数复制原始对象的每个成员来制作一个新的 Test。默认情况下C++编译器会生成一个复制构造函数:当把所有变量值从旧对象复制到新对象时,就会有两个指针指向内存中的同一个数组。这本质上并不坏,但析构函数将尝试删除同一个数组两次,因此出现”double free detected”运行时错误。
$ valgrind --leak-check=yes ./a.out ==21832== Memcheck, a memory error detector ==21832== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==21832== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info ==21832== Command: ./a.out ==21832== myArray addr 0x5b7ff40 ==21832== ==21832== HEAP SUMMARY: ==21832== in use at exit: 0 bytes in 0 blocks ==21832== total heap usage: 6 allocs, 6 frees, 74,376 bytes allocated ==21832== ==21832== All heap blocks were freed -- no leaks are possible ==21832== ==21832== For counts of detected and suppressed errors, rerun with: -v ==21832== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)