我正在用delphi编写一个通用的图形库。
下面的代码显示了TGraph和Tvertex的实现
/// TGRAPH ....
constructor TGraph<Tdata>.Create( ...);
begin
// the graph owns its vertices - by freeing of the graph one frees the vertex list!
_vertices := TObjectList < TVertex < Tdata >>
.Create(TVertex<Tdata>.createVertexComparer(), true);
_edges := TObjectList < TEdge < Tdata >>
.Create(TEdge<Tdata>.createEdgeComparer(), true);
end;
// destroy the graph and all its elemenst!
destructor TGraph<Tdata>.Free;
begin
_edges.Free;
_vertices.Free;
end;
/// Tvertex ......
class function TVertex<T>.createVertexComparer(): IComparer<TVertex<T>>;
begin
Result := TDelegatedComparer < TVertex < T >>.Create(
function(const Left, Right: TVertex<T>): Integer
begin
Result := Left.Compare(Right);
end);
end;
constructor TVertex<T>.Create(withID: Integer);
begin
F_neighbours := TObjectList < TVertex < T >>
.Create(TVertex<T>.createVertexComparer(), true);
vertex_id := withID;
end;
function TVertex<T>.Compare(const v: TVertex<T>): Integer;
begin
Result := (self.fId - v.vertex_id);
end;
destructor TVertex<T>.Free;
begin
F_neighbours.Free;
// F_neighbours := nil;
FreeAndNil(Fdata);
end;
如果我运行代码,我会发现FastMM4的内存泄漏报告,如屏幕转储中所示。 我不明白为什么TdelegatedComparer漏了?
答案 0 :(得分:6)
析构函数TGraph.Free;
析构函数TVertex.Free;
正确的析构函数名称为Destroy
,必须将其声明为override
,因为virtual
中的TObject
:
type
TGraph<T> = class(...)
...
public
...
destructor Destroy; override;
end;
destructor TGraph<T>.Destroy;
begin
_edges.Free;
_vertices.Free;
inherited; // <-- and don't forget this
end;
type
TVertex<T> = class(...)
...
public
...
destructor Destroy; override;
end;
destructor TVertex<T>.Destroy;
begin
F_neighbours.Free;
// F_neighbours := nil;
FreeAndNil(Fdata);
inherited;
end;