Will using delete with a base class pointer cause a memory leak?

后端 未结 5 1128
星月不相逢
星月不相逢 2021-02-05 08:38

Given two classes have only primitive data type and no custom destructor/deallocator. Does C++ spec guarantee it will deallocate with correct size?

struct A { in         


        
5条回答
  •  抹茶落季
    2021-02-05 09:09

    This is undefined behaviour - maybe everything's fine, maybe whetever goes wrong. Either don't do it or supply the base class with a virtual destructor.

    In most implementations this will not leak - there're no heap-allocated member functions in the class, so the only thing needed when delete is done is to deallocate memory. Deallocating memory uses only the address of the object, nothing more, the heap does all the rest.

提交回复
热议问题