I.T. Discussion Community!
-Collapse +Expand
Delphi
Search Delphi Group:

Advanced
-Collapse +Expand Delphi To/From
To/FromCODEGuides
-Collapse +Expand Delphi Store
PRESTWOODSTORE

Prestwood eMagazine

June Edition
Subscribe now! It's Free!
Enter your email:

   ► KBProgrammingDelphi for W...OOP   Print This     
 
Delphi OOP:
Delphi Destructor (Free or FreeAndNil)
 
Posted 10 years ago on 10/24/2008 and updated 1/23/2009
Delphi Code Snippet:
 A flashcard from our Delphi Flashcards Library
 A code snippet from our Delphi Code Snippets Page
 Tags: Delphi , Destructor

KB101432



General Info: Class Destructor

A special class method called when an object instance of a class is destroyed. With some languages they are called when the object instance goes out of scope, with some languages you specifically have to call the destructor in code to destroy the object, and others use a garbage collector to dispose of object instances at specific times.

Desctructors are commonly used to free the object instance but with languages that have a garbage collector object instances are disposed of when appropriate. Either way, destructors or their equivalent are commonly used to free up resources allocated in the class constructor.

Languages Focus: Destructor

Are object instances freed with a garbage collector? Or, do you have to destroy object instances.

Delphi Destructor

Object Pascal uses a standard virtual destructor named Destroy which is called by the standard Free method. All objects are dynamic, so you need to call MyObject.Free method or the FreeAndNil(MyObject) routine for each object you create.

Syntax Example:
var
MyObject: TObject;
begin
MyObject := TObject.Create;
 
  //Use it...
  
  MyObject.Free
  //Or use...FreeAndNil(MyObject);
end;

More Info

Definition:  Class Destructor

Comments

1 Comments.
Share a thought or comment...
First Comment
Comment 1 of 5

WIth Delphi 5 and later, it is my understanding it is better to use

FreeAndNil(objMyObject);

Thoughts and comments?

Posted 10 years ago

Comment 2 of 5

Hmmm...sure, that's a good rule of thumb and thanks for adding the info here (I added it to the flashcard above too). Bottom line.

However, to further the discussion I guess it depends on the situation. It is a routine and not a class method so using Free "feels" more OOP to me so I tend to use it with simple OOP examples when giving demos. ((I know, that's a pretty weak excuse but I think it helps with new coders.)) You do have to be careful to only pass TObjects to this routine too. My own rule of thumb with larger applications is that I use Free when doing simple controlled tasks and FreeAndNil with more complicated things.

Also, when do we stop writing extra checks? You could be even more complete and do something like the following:

If Assigned(MyObject) then
FreeAndNil(MyObject)
Else
MyObject := nil;

If by some chance MyObject was not assigned to begin with, then FreeAndNil() will never get called and therefore MyObject will never get set to nil.

Should Be NilAndFree

Finally a minor point but because we're getting into it a bit, I thought it might be important because FreeAndNil actually does the opposite. You can run into problems accessing the object variable while it's being destroyed.

For reference, here are the three VCL code routines in discussion:

In System Unit:

//TObject.Free
procedure TObject.Free;
begin
  if Self <> nil then
    Destroy;
end; 
 
//TObject.Destroy
destructor TObject.Destroy;
begin
end;

In SysUtils unit:

//FreeAndNil
procedure FreeAndNil(var Obj);
var 
  Temp: TObject;
begin 
  Temp := TObject(Obj); 
  Pointer(Obj) := nil; 
  Temp.Free;
end;

 

Posted 10 years ago

Comment 3 of 5

Whether to use Free, or FreeAndNil, is an interesting topic.  It depends on the circumstances.

My rule of thumb is that if an object is local (that is, it's reference variable will soon go out of scope) just use Free.  But if the object is more "global," use FreeAndNil.

A classic example is a form that will create and show another form.  This is often done within the scope of a button click handler, or an ActionItem's Execute method:

procudure MyForm.Button1Click(Sender : TObject);
var 
  StudentForm : TStudentForm;
begin
  StudentForm := TStudentForm.Create(Self);
  StudentForm.ShowModal;
  StudentForm.Free;
end;

In the above snippet, the local variable, StudentForm, isn't accessible outside of the click handler, and it will go out of scope fairly soon.  In this case, I think Free is sufficient.

However, if I'd made my reference variable more "global," say as a private member, FStudentForm, of TMyForm, any and every method of that class has access to it. In that case, I'll use FreeAndNil:

procedure MyForm.Button1Click(Sender : TObject);
begin
  if (FStudentForm = nil) then
    FStudentForm := TStudentForm.Create(Self);
  FStudentForm.ShowModal;
  FreeAndNil(FStudentForm);
end;

Just to play it safe, you'll probably want to set FStudentForm to nil in TMyForm's OnCreate event.

Of course, it does no harm to use FreeAndNil wherever it's legal (As Mike says, the argument to FreeAndNil must be a TObject, or descendant thereof).

Posted 10 years ago

Comment 4 of 5

Hi Mike, my name is April Russell and I believe I have an account with PrestwoodBoard many years ago. Just this morning, I felt homesick on using Delphi when I got an Ad that Delphi is dead. juegos friv gratis online, free run 3 unblocked.

Anyway, I was surprised when I saw your comment that semicolon at the end of Javascript statement is optional. It may be optional in some cases but NOT in this:

//Semicolons are optional:
document.write("Hello3")
document.write("Hello4")
---
April Russell
Posted 5 months ago

Latest Comment
Comment 5 of 5

I am doing a project on this and I don't have minimum knowledge on it. The best paper writing service has recommended this site to me. I have learned many things here.

Posted 9 days ago
 
Write a Comment...
...
Sign in...

If you are a member, Sign In. Or, you can Create a Free account now.


Anonymous Post (text-only, no HTML):

Enter your name and security key.

Your Name:
Security key = P1226A1
Enter key:
Code Contributed By Mike Prestwood:

Mike Prestwood is a drummer, an author, and creator of the PrestwoodBoards online community. He is the President & CEO of Prestwood IT Solutions. Prestwood IT provides Coding, Website, and Computer Tech services. Mike has authored 6 computer books and over 1,200 articles. As a drummer, he maintains play-drums.com and has authored 3 drum books. If you have a project you wish to discuss with Mike, you can send him a private message through his PrestwoodBoards home page or call him 9AM to 4PM PST at 916-726-5675 x205.

Visit Profile


Linked Certification Question(s)

The following are practice certification questions with answers highlighted. These questions were prepared by Mike Prestwood and are intended to stress an important aspect of this KB post. All our practice questions are intended to prepare you generally for passing any certification test as well as prepare you for professional work.

Beginner

1 Beginner Level Question

Question #1: Multiple Choice

Given the following code:

var
MyObject: TObject;
begin
MyObject := TObject.Create;
 
  //Use it...  
end;
Answer:
1. 

Delphi has a garbage collector so you do not have to dispose of the object after the "Use it" comment but optionally you can dispose of additional resources created in the constructure overriding the Finalize() method and calling MyObject.Free().

2. 

Delphi does not have a garbage collector so you have to dispose of the object after the "Use it" comment with MyObject.Dispose().

3. 

Delphi does not have a garbage collector so you have to dispose of the object after the "Use it" comment with either MyObject.Free() or FreeAndNil(MyObject).


 KB Article #101432 Counter
20711
Since 10/24/2008
-
   Contact Us!
 
PrestwoodBoards.com was developed and is maintainted by me. Do you have a question or suggestion? Do you see a problem? Contact me now. My goal is to build an ad-free and spam-free source of I.T. information with many contributers (ok to promote your website/company in your bio). Yes, my company Prestwood IT Solutions is mentioned in my bio which shows with every post, but you can contribute and promote your pet project too!

1,719 People Online Now!!  
Sign In to see who's online now!  Not a member? Join now. It's free!
Show more stats...


©1995-2018 PrestwoodBoards  [Security & Privacy]
Professional IT Services: Coding | Websites | Computer Tech