The following code lowers my belief that I know C ++ more or less. Why valgrind
does not display memleak here? Why I expect memleaks:
B
larger than A
: it contains an additional element; therefore, assignment must be separated by class fields.- ~ A () does not have a virtual dtor. Therefore, when we call
delete a
, only ~A()
should be called, and the memory allocated in B will be lost.
But I get that dtors calling order: ~ A (), ~ B (), ~ A (). Why?
struct A { ~A() { std::cerr << "~A" << std::endl; } }; struct B : A { int* data; B() : data(new int[20]) {} ~B() { std::cerr << "~B" << std::endl; delete [] data; } };
main()
:
A* a = new A; B* b = new B; *a = *b; delete a; delete b;
UPD: I am ashamed! I confused the removal of an object with a pointer to the base class when it was supposed to call a virtual dtor. Here is just the contents of the class. Thanks everyone!
source share