我有一小段代码作为打击
class singler { private: singler() { _id = id++; }; public: ~singler() { cout<<"In destructor of "<<_id<所以你可以看到对象的析构函数将被调用两次,作为证明,我编译并运行它,它给出了输出
In destructor of 0 In destructor of 0问题在于valgrind,它不会抱怨任何东西,valgrind输出如下== 2
0408== Memcheck, a memory error detector ==20408== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al. ==20408== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info ==20408== Command: a.out ==20408== In destructor of 0 In destructor of 0 ==20408== ==20408== HEAP SUMMARY: ==20408== in use at exit: 0 bytes in 0 blocks ==20408== total heap usage: 1 allocs, 1 frees, 4 bytes allocated ==20408== ==20408== All heap blocks were freed -- no leaks are possible ==20408== ==20408== For counts of detected and suppressed errors, rerun with: -v ==20408== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)那么如何有效地检测这类错误呢?(我的意思是使用一些工具,至少会告诉我是否有任何问题,如果是的话,它在哪里?)
您的程序中没有损坏,valgrind在您的情况下工作正常.
确实创建了两个对象.第一个对象在堆上分配,第二个对象是第一个对象的副本.这就是为什么你看到析构函数被调用两次.