Reputation: 317
I have this example method below
procedure ReadData(var data:TDataSet)
begin
if Assigned(data) then
data.Free;
data:=TDataSet.Create(nil);
....
end;
.....
procedure SomethingProcedure()
var
dataSet:TDataset;
begin
ReadData(dataSet);
end;
if I debugged and I place breakpoint on Assigned checking, data.Free always executed, and I saw on watch list, data always inaccessible value
My point is SomethingProcedure is access for many other procedure, and I want data parameter if it assigned (already created TDataset object), free it first, but if not assigned (not created object), free command doesn't execute, but free statement always executed, either "data" object created or not
How I can check my object already created or not
Upvotes: 2
Views: 3423
Reputation: 58431
You have some issues with your code example
dataset
but pass data
in your Init
procedureif
statement doesn't have a then
in your ReadData
procedureAll in all, you can not have been debugging the example you've given so I'm going to make some assumptions here.
I believe your actual problem is coming from the fact that local, not finalized variables do not get initialized to zero/nil. The dataset
variable in your Init
procedure contains whatever garbage happens to be at the location the variable points to.
Which variables are initialized when in Delphi?
As you don't initialize the local variable dataset
(something you should always do with local variables), Assigned
will return true (all it does is check for nil) and free
will get called.
Most of the time and if you are lucky, the call to free will throw an AV. Worst case, it will succeed and you will have a really hard time figuring out why something is going wrong.
Edit
I assume by your edit that you mean that ReadData
is called in many other procedures?
If that's the case, there really is not a lot you can (or for that matter should) do to protect you from callers passing in garbage. What you should do is fix the callers.
Fix the root cause, not the symptoms
Upvotes: 4
Reputation: 6979
First of all, you do not have to check your data
object for assignment. It is perfectly safe to call Free
method when data
is pointing to nil
.
As for the reason why you can not see on what the data
is pointing to: you probably need to turn off the optimization for your project. To do this go to: Project > Options > Delphi Compiler > Compiling (this may vary depending on your Delphi version) and switch Optimization to False.
Upvotes: 3