I have a small block of code as blow
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;
}
So you can see that the destructor of the object will be called twice, as a proof, i compiled and ran it, it gave output as
In destructor of 0
In destructor of 0
Problem is in valgrind, it does not complain for anything, the valgrind output is as below ==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)
So how to detect this type of errors efficiently? ( i mean using some tool which will atleast tell me if there is any problem, and if yes, where is it? )
There are no corruption in your program, and valgrind worked fine in your case.
Two objects are indeed created. The first object is allocated on a heap, and the second is a copy of the first object. That is why you see the destructor called twice.