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

后端 未结 5 1147
星月不相逢
星月不相逢 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 08:53

    According to the C++ standard, what you have is undefined behaviour - this may manifest itself as a leak, it may not, For your code to be correct you need a virtual destructor.

    Also, you do not need that (A*) cast. Whenever you find yourself using a C-style cast in C++, you can be fairly sure that either it is unecessary, or your code is wrong.

    0 讨论(0)
  • 2021-02-05 09:04

    It will deallocate with correct size, because the size to be deallocated is a property of the heap memory region you obtained (there is no size passed to free()-like functions!).

    However, no d'tor is called. If 'B' defines a destructor or contains any members with a non-trivial destructor they will not be called, causing a potential memory leak. This is not the case in your code sample, however.

    0 讨论(0)
  • 2021-02-05 09:05

    For only primitive data I believe you're fine. You might legitimately not want to incur the cost of a v-table in this case. Otherwise, a virtual d'tor is definitely preferred.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-05 09:14

    Unless the base class destructor is virtual, it's undefined behaviour. See 5.3.5/4:

    If the static type of the operand [of the delete operator] is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behaviour is undefined.

    0 讨论(0)
提交回复
热议问题