Rule of thumb for dealing with allocating member: every new
/new[]
should be paired with exactly one delete
/delete[]
. If you are missing the delete
, then you have a memory leak (you have allocated memory that you never clean up). If you are delete
-ing multiples times, as you are doing in this code example, you will have memory corruption issues.
How are you delete
-ing multiple times? In main()
, you allocate a pointer:
int* myptr = new int;
You give a copy of that pointer to your test
object, obj
. Then, at the end of the scope we have:
{
// ...
delete myptr;
~test(); // implicit, which also does delete myptr
}
Only one of those two places should be responsible for delete
-ing the pointer. Which one is based on the semantics of your code. Does test
own the pointer? In which case, it should delete
it but main()
should not. Does it simply observe the pointer? In which case, it should not delete
it. With C++11, we have new smart pointers to express this idea better.
I'd encourage you to browse the definitive C++ book list as concepts like this are very crucial to understanding C++ but also very difficult to explain properly in a short Q&A format.