瓦尔格林德并不抱怨内存损坏



>我有一小块代码作为打击

class singler
{
    private:
        singler() { _id = id++; };
    public:
        ~singler() { cout<<"In destructor of "<<_id<<endl;};
        static singler* allocate() { singler* p = new singler(); return p; };
        static int id;
        int _id;
};
int singler::id = 0;
singler& create_new(singler*& ptr)
{
    singler * p = singler::allocate();
    ptr = p;
    return (*p);
}
int main()
{
    singler* ptr;
    singler obj = create_new(ptr);
    delete ptr;
}

所以你可以看到对象的析构函数将被调用两次,作为证明,我编译并运行了它,它给出了输出

In destructor of 0
In destructor of 0

问题出在瓦尔格林德,它不抱怨任何事情,瓦尔格林德输出如下==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 在你的情况下工作得很好。

确实创建了两个对象。第一个对象在堆上分配,第二个对象是第一个对象的副本。这就是为什么你看到析构函数被调用两次的原因。

相关内容

  • 没有找到相关文章

最新更新