Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C/C++: Общие вопросы > Отчистка памяти под указателем


Автор: Rickert 24.9.2009, 05:11
Есть класс B, потомок класса A.
Работаю с указателем на объект типа А, который указывает на объект типа B.
Код

B* b = new B;
A* a = (A*)b;
...
a->someCommonDoings();
...
delete (B*)a;

Или я могу удалить так:
Код
delete a;

?

Автор: t_gran 24.9.2009, 05:34
Это всё зависит от того, определили ли вы диструкторы и как. 
Если вы их не определяете, то в случае:
Код

delete a;

Вызовется диструктор класса A

В случае:
Код

delete (B*)a;

Вызовется диструктор, сначала B, а потом A

Но, чтобы постоянно не писать
Код

delete (B*)a;


Для этого диструкторы, обычно, делаются виртуальными, тогда компилятор сам определит какой диструктор вызвать. И тогда вы сможете писать:
Код

delete a;


Автор: Rickert 24.9.2009, 06:00
Действительно так.
solved smile 

Автор: Annihilator 24.9.2009, 06:08
Смотрим стандарт
Цитата

Delete 5.3.5

3- In the first alternative (delete object), if the static type of the operand 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 behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.*

4- The cast-expression in a delete-expression shall be evaluated exactly once. If the delete-expression calls the implementation deallocation function (basic.stc.dynamic.deallocation), and if the operand of the delete expression is not the null pointer constant, the deallocation function will deallocate the storage referenced by the pointer thus rendering the pointer invalid. [Note: the value of a pointer that refers to deallocated storage is indeterminate. ] 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)