2

I'd like to check how deleting an object via base-type pointer works. First case:

Base{int x};
Derived : Base {
int a;
};
Base *p = new Derived;
delete p;

Second case:

Base{int x};
Derived: Base {
vector<int> v;
}
Base *p = new Derived;
delete p;

1) Is it right that in first case there can't be any memory leaks and virtual destructor is not necessary? 2) Is it right that in second case there might be memory leaks as std::vector is likely implied via some dynamic memory allocation? And this means that virtual destructor is necessary in the second case?

Dmitry J
  • 867
  • 7
  • 20
  • The behaviour of `delete p` is undefined if `*p` is not a complete object and does not have a virtual destructor. – Kerrek SB Jul 03 '16 at 20:24
  • By "is not a complete object" you mean that I made class Base empty? Ok, I edited the question so Base is not empty anymore. My question is more about whether it makes difference when I have std::vector in Derived. – Dmitry J Jul 03 '16 at 21:11
  • But anyway, they say that deleting via base-pointer without virtual destructor is undefined. I just wonder why here: [link](http://stackoverflow.com/questions/8772227/deleting-a-derived-object-via-a-pointer-to-its-base-class) they said that without dynamic memory allocations it's ok. – Dmitry J Jul 03 '16 at 21:17
  • You need to be more precise: It is undefined behaviour to delete an object through a pointer to a base subobject if the base class does not have a virtual destructor. "Incomplete object" means "not a complete object", i.e. the subobject of another object. – Kerrek SB Jul 03 '16 at 22:26
  • According to the standard, it causes undefined behavior, but if you really want to do it, examine the disassembly. Since `delete new Base;` is defined behavior, it might be the case that `delete (Base*)(new Derived);` follows the same code path, resulting in a call to `Base::~Base()` and then a call to `free(ptr)` to deallocate the memory, and `free(ptr)` is likely smart enough to figure out the size of the memory region that was originally allocated. – evan Jul 03 '16 at 22:54

0 Answers0