Originale-mail to me for new edition

 

Destructors

 

A destructor is a special method that destroys the object where it is called and deallocates its memory. The declaration of a destructor looks like a procedure declaration, but it begins with the word destructor. Examples:

destructor Destroy;

destructor Destroy; override;

Destructors must use the default register calling convention. Although a class can have more than one destructor, it is recommended that each class override the inherited Destroy method and declare no other destructors.

To call a destructor, you must reference an instance object. For example,

MyObject.Destroy;

When a destructor is called, actions specified in the destructor implementation are performed first. Typically, these consist of destroying any embedded objects and freeing resources that were allocated by the object. Then the storage that was allocated for the object is disposed of.

Here is an example of a destructor implementation.

destructor TShape.Destroy;

begin

  FBrush.Free;

  FPen.Free;

  inherited Destroy;

end;

The last action in a destructor’s implementation is typically to call the inherited destructor to destroy the object’s inherited fields.

When an exception is raised during creation of an object, Destroy is automatically called to dispose of the unfinished object. This means that Destroy must be prepared to dispose of partially constructed objects. Because a constructor sets the fields of a new object to zero or empty values before performing other actions, class-type and pointer-type fields in a partially constructed object are always nil. A destructor should therefore check for nil values before operating on class-type or pointer-type fields. Calling the Free method (defined in TObject), rather than Destroy, offers a convenient way of checking for nil values before destroying an object.

 

Topic groups

 

See also

Calling conventions

Constructors

Exceptions: Overview

Inheritance and scope

Inherited

Method declarations and implementations

Methods: Overview

 

 

译文

 

析构器

 

析构器是一个特殊的方法,它用于销毁调用它的对象并释放内存。析构器的声明与过程声明相似,不同的是,析构器的声明以保留字destructor开始。例如:

destructor Destroy;

destructor Destroy; override;

析构器必需使用缺省的register调用约定。尽管一个类可以有多于一个析构器,但还是推荐每个类都覆盖(override)继承的析构器并且不再声明其他的析构器。

要调用析构器,必需引用实例对象。例如,

MyObject.Destroy;

当一个析构器被调用时,析构器实现中指定的动作将被首先执行。典型的操作有,销毁所有由析构器所属对象内含的对象并释放其占用的资源,然后释放分配给析构器所属对象的存储空间。

下面是析构器实现的例子。

destructor TShape.Destroy;

begin

  FBrush.Free;

  FPen.Free;

  inherited Destroy;

end;

析构器实现中最后一个动作通常是调用继承得到的析构器以销毁对象中继承得到的域。

在创建对象对象的过程中,当异常发生时,析构器Destroy会被自动调用以释放未完成的对象。这意味着析构器Destroy必需为释放部分构造的对象做好准备。构造器在执行其他动作之前会对新对象的域置零或空值,而在部分构造的对象中,类类型和指针类型的域总是nil。因此析构器需要在对类类型或指针类型操作之前进行空指针nil的检查。调用Free(在TObject对象中定义)方法优于调用Destroy,因为Free方法提供了在销毁对象之前对nil值的检查。

 

主题组

 

相关主题

调用约定

构造器

异常:概述

继承和作用域

继承(Inherited

方法声明和实现

方法:概述

 

 

编者注

有关destructor一词,本意是“销毁者”,可以译做“销毁器”。本参考中为了将constructordestructor译成字面有联系的两个词,所以分别译做“构造器”和“析构器”。