Double free or corruption when using destructor
This question already has an answer here:
This is because you make copies of your Element when you push it in the vector, but the vtx is not duplicated on copy, so an the end of main(), you will have three Elements pointing to the same vtx. When the program terminates, all three of them will try to delete the same int array.
When you add elm[0]
to vec
, copies of elm[0]
are stored in vec
. Since you haven't defined a copy constructor, the compiler used the default one -- which performs a member by member copy. In this case, it keeps a copy of the pointer vtx
. Now you have three objects pointing to the same memory.
When vec
gets destructed, it calls the destructor on two of those objects. They each try delete
on the same pointer. Hence the error.
If you want to avoid errors like these, check out Rule of Three.
链接地址: http://www.djcxy.com/p/73178.html上一篇: 为什么我的析构函数被调用,我该如何解决它
下一篇: 当使用析构函数时,释放或损坏