TCollectionItem and destructor method in delphi
Hey, Could anyone tell me if the implementations of the Destructor in the following example are correct and the same?
TTaskItem = class 开发者_JAVA技巧(TCollectionItem)
private
FTask: TTask;
public
constructor Create(Collection: TCollection);override;
destructor Destroy;override;
property Task: TTask read FTask write FTask;
end;
// //Are these two the same?
destructor TTaskItem.Destroy;
begin
inherited Destroy;
end;
destructor TTaskItem.Destroy;
begin
inherited;
end;
Yes they are both correct and both the same.
Typically you would have created FTask
in the constructor and the destructor would read:
destructor TTaskItem.Destroy;
begin
FTask.Free;
inherited;
end;
Always remember to include override
when you declare your destructor, as you have done. If you forget this then it won't run. That's a classic source of memory/resource leaks.
You should call inherited
as the first action in a constructor and as the last action of the destructor. This arranges that creation and destuction happen in reverse order which is invariably what is needed.
For example you might create two objects, A and B, and B has a reference to A which is passed in to the constructor of B. Clearly you have to create A first:
A := TClassA.Create;
B := TClassB.Create(A);
When destroying you want to destroy B first in case it does anything with the reference to A that it holds. If you did it the wrong way round, B would be calling methods on A which had already been destroyed. So your destructor reads:
B.Free;
A.Free;
精彩评论