gpt4 book ai didi

delphi - 内存泄漏 T 委托(delegate)比较器

转载 作者:行者123 更新时间:2023-12-02 18:46:38 24 4
gpt4 key购买 nike

我正在用 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 的内存泄漏报告,如屏幕转储中所示。我不明白为什么 TdeleatedComparer 会泄漏?

enter image description here

最佳答案

destructor TGraph.Free;

destructor TVertex.Free;

正确的析构函数名称是 Destroy ,并且必须将其声明为 override因为它是virtualTObject :

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;

关于delphi - 内存泄漏 T 委托(delegate)比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23962176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com