考虑以下示例(我使用的是Delphi XE):
program Test;
{$APPTYPE CONSOLE}
type
TTestClass<T> = class
private
class constructor CreateClass();
public
constructor Create();
end;
class constructor TTestClass<T>.CreateClass();
begin
// class constructor is not called. this line never gets executed!
Writeln('class created');
end;
constructor TTestClass<T>.Create();
begin
// this line, of course, is printed
Writeln('instance created');
end;
var
test: TTestClass<Integer>;
begin
test := TTestClass<Integer>.Create();
test.Free();
end.
Run Code Online (Sandbox Code Playgroud)
从不调用类构造函数,因此不会打印"创建类"行.但是,如果我删除泛化并TTestClass<T>
进入标准类TTestClass
,一切都按预期工作.
我是否遗漏了仿制药?或者它根本不起作用?
对此的任何想法都会受到关注!
谢谢, - 斯特凡 -
使用ToBytes方法(见下文)将AnsiString的硬类型转换替换为TBytes(字符串数组)后,Delphi报告没有内存泄漏 - 但是,如果将TBytes值传递给具有a的方法,则Free Pascal 2.6.2会显示泄漏类型的参数Pointer
.
以下代码泄漏内存:
program project1;
{$mode delphi}
uses
SysUtils;
function ToBytes(const AValue: AnsiString): TBytes;
begin
SetLength(Result, Length(AValue)); // <-- leak (ine 10)
if Length(AValue) > 0 then
Move(AValue[1], Result[0], Length(AValue));
end;
procedure Send(P: Pointer);
begin
end;
begin
Send(ToBytes('test'));
SetHeapTraceOutput('heaptrace.log');
end.
Run Code Online (Sandbox Code Playgroud)
内存泄漏报告:
Call trace for block $001C5CC0 size 12 $00401586 TOBYTES, line 10
of project1.lpr $00401622 main, line 21 of project1.lpr
Run Code Online (Sandbox Code Playgroud)
如果我将Send方法更改为采用TBytes类型的参数,则内存泄漏将消失.
综述:
请查看以下知识渊博的评论.
================================================== ============
我已经看到了managed types
很多stackoverflow Delphi主题中提到的术语.例如,它在主题中提到correctly initializing/finalizing
.但是,当我谷歌时managed types
,似乎大多数链接都与C++或.NET有关.例如,请参阅MSDN页面.有人可以帮助评论Delphi中定义的托管类型吗?鉴于Delphi for POSIX/MacOS正在诞生,是Windows特有的托管类型吗?感谢您提前付出的努力和时间!
PS:主题correctly initializing/finalizing
:
在Delphi中初始化哪些变量?
delphi变量是否默认使用值初始化?
我应该如何在Delphi 7析构函数中释放一组对象?
在Delphi 2009中,我是否需要释放变体数组?
delphi ×2
compiler-bug ×1
delphi-xe ×1
fpc ×1
freepascal ×1
generics ×1
managed ×1
memory-leaks ×1
types ×1