【发布时间】:2011-05-29 04:13:01
【问题描述】:
环境:德尔福 2007
Anyhoo,我刚刚实现的一个特别复杂的记录是破坏内存(后来导致“无效指针操作”错误)。
这是内存垃圾代码的示例:
sSignature := gProfiles.Profile[_stPrimary].Signature.Formatted(True);
在我第二次调用它时,我得到“无效的指针操作”
如果我这样称呼它就可以了:
AProfile := gProfiles.Profile[_stPrimary];
ASignature := AProfile.Signature;
sSignature := ASignature.Formatted(True);
后台代码:
gProfiles: TProfiles;
TProfiles = Record
private
FPrimaryProfileID: Integer;
FCachedProfile: TProfile;
...
public
< much code removed >
property Profile[ProfileType: TProfileType]: TProfile Read GetProfile;
end;
function TProfiles.GetProfile(ProfileType: TProfileType): TProfile;
begin
case ProfileType of
_stPrimary : Result := ProfileByID(FPrimaryProfileID);
...
end;
end;
function TProfiles.ProfileByID(iID: Integer): TProfile;
begin
<snip>
if LoadProfileOfID(iID, FCachedProfile) then
begin
Result := FCachedProfile;
end
else
...
end;
TProfile = Record
private
...
public
...
Signature: TSignature;
...
end;
TSignature = Record
private
public
PlainTextFormat : string;
HTMLFormat : string;
// The text to insert into a message when using this profile
function Formatted(bHTML: boolean): string;
end;
function TSignature.Formatted(bHTML: boolean): string;
begin
if bHTML then
result := HTMLFormat
else
result := PlainTextFormat;
< SNIP MUCH CODE >
end;
好的,所以我在记录中的记录中有一个记录,这接近于 Inception 级别的混乱,我首先承认这不是一个真正的好模型。显然,我将不得不对其进行重组。我想从各位大师那里更好地理解它为什么会破坏内存(与创建然后释放的字符串对象有关......)这样我就可以避免将来犯这些错误。
谢谢
【问题讨论】:
-
记录类型的属性?我很确定那根本不应该编译。 “无效的指针操作”意味着你正在释放一些已经被释放的东西,或者释放的东西从来没有引用过动态分配的内存。
-
@Rob:为什么不应该编译?尽管无法分配给记录成员,但仍允许记录属性 (`Obj.Record.Member := 'blub')
-
+1 记录属性是完全合理的,例如使用运算符重载的复数记录呢?
标签: delphi delphi-2007 records