【发布时间】:2016-03-02 21:46:30
【问题描述】:
我使用 Delphi Seattle。
当我尝试释放我创建的对象时出现问题。
我在此站点(以及其他站点)中搜索了已针对此问题发布的答案,但它们都有些不同。根据这些讨论,我的代码应该可以工作,但显然有些地方不太对劲。
所以,我需要帮助...
执行流程:
a) 在表单 fmLoanRequest 中,我创建了一个基于 Class TStorageLoan(TLoan 的子类)的对象。构造函数将所有类型的值加载到对象的一些属性中(现在在这里显示)。
b) 稍后,我将对象的地址传递给另一种形式 (fmLoan) 到适当的公共变量。 fmLoan 是所有用户处理 Loan 内容的形式。请注意,当我们在 fmLoan 中时,fmLoanRequest 保持原样。当 fmLoan 关闭时,我们将返回 fmLoanrequest。
c) 显示 fmLoan 表单(并显示对象中的数据 - 一切正常)。
d) 当关闭 fmLoan 时,会调用一个过程来释放 Loan 对象 - 如果它已被分配(参见 second 代码 sn-p 的第 10 行)。这似乎工作正常(没有错误)。
e) 执行下面第 14 行中的代码时出现“无效指针操作”错误:( if Assigned(oLoan) then oLoan.Free; )。
我添加了这一行以确保如果 fmLoan 出于某种原因没有处理它,该对象将被释放。我意识到此时对象已被释放,但“if Assgned()”不应该阻止不必要的对象释放吗?
form fmLoanRequest的部分代码(我添加了一些行号以供参考)
1 // In form fmLoanRequest
2 // Create new Loan Object (from a Loan sub-class as it happens)
3 // Create the object here; Object address will be passed to fmLoan later for handling.
4 oLoan := TStorageLoan.Create(iNewLoanID);
5 ...
6 ...
7 fmLoan.oLoan := oLoan; // pass the address to the other form
8 fmLoan.show;
9 // User would click the 'btnClose' at this point. See event code below.
10 ...
11 ...
12 procedure TfmLoanRequests.btnCloseClick(Sender: TObject);
13 begin
14 if Assigned(oLoan) then oLoan.Free; // <--- ERROR HERE
15 fmLoanRequests.Close;
16 end;
form fmLoan的部分代码(我添加了一些行号以供参考)
1 //Form fmLoan
2 ...
3 public
4 oLoan : TLoan;
5 ...
6 // In form fmLoan, I call the following upon closing the Form
7 // in the OnClick event of the 'btnClose' button.
8 Procedure TfmLoan.Clear_Loan_Object;
9 begin
10 if Assigned(oLoan) then oLoan.Free; // <-- THIS WORKS FINE
11 end;
我应该尝试不同的方法吗?
我是否应该删除该行(第 14 行 - 第一个代码 sn-p)并希望最好。这根本不是我正确编码的理念!
我是不是走错路了?
注意:我显然不使用指针。
任何帮助将不胜感激!
【问题讨论】:
-
您可以在所有使用 oLoan.free 的地方使用 FreeAndNil(oLoan)。这样,您对 Assigned(oLoan) 的测试将在您期望的时候返回 true。