RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
SysUtils.FreeAndNil Function

Frees an object reference and replaces the reference with nil (Delphi) or NULL (C++).

Pascal
procedure FreeAndNil(var Obj);
C++
FreeAndNil( Obj);

SysUtils

Use FreeAndNil to ensure that a variable is nil (Delphi) or NULL (C++) after you free the object it references. Pass any variable that represents an object as the Obj parameter.

Warning: Obj must be an instance of a TObject descendant.
 

C++ Examples: 

 

/*
This code displays a Save Picture dialog box with the
TBitmap default extension that is added automatically to
files that are given no extension. Confirm that the
bitmap file has been saved under the filename and path
specified.
*/
void __fastcall TForm1::Button1Click(TObject *Sender)
{
  AnsiString NewFileName, OldFileName;
  TFileStream *NewFile, *OldFile;
  SavePictureDialog1->DefaultExt = GraphicExtension(__classid(Graphics::TBitmap));
  SavePictureDialog1->Filter = GraphicFilter(__classid(Graphics::TBitmap));
  OldFileName = "factory.bmp";
  if (SavePictureDialog1->Execute())
  {
    NewFileName = SavePictureDialog1->FileName;
    OldFile = new TFileStream(OldFileName, (fmOpenRead | fmShareDenyWrite));
    try
    {
      NewFile = new TFileStream(NewFileName, (fmCreate | fmShareDenyRead));  
      try
      {
        NewFile->CopyFrom(OldFile, OldFile->Size);
      }
      __finally
      {
        FreeAndNil(&NewFile);
      };
    }
    __finally
    {
      FreeAndNil(&OldFile);
    };
  };
}

void __fastcall TForm1::FormCreate(TObject *Sender)
{
  Image1->Picture->LoadFromFile("../factory.bmp");
}

 

Delphi Examples: 

{
This code displays a Save Picture dialog box with the
TBitmap default extension that is added automatically to
files that are given no extension. Confirm that the
bitmap file has been saved under the filename and path
specified.
}
procedure TForm1.Button1Click(Sender: TObject);
var NewFileName, OldFileName: string;
    NewFile, OldFile: TFileStream;
begin
  SavePictureDialog1.DefaultExt := GraphicExtension(TBitmap);
  SavePictureDialog1.Filter := GraphicFilter(TBitmap);
  OldFileName := 'factory.bmp';
  if SavePictureDialog1.Execute then
  begin
    NewFileName := SavePictureDialog1.FileName;
    OldFile := TFileStream.Create(
      OldFileName, fmOpenRead or fmShareDenyWrite);
    try
      NewFile := TFileStream.Create(
        NewFileName, fmCreate or fmShareDenyRead);
      try
        NewFile.CopyFrom(OldFile, OldFile.Size);
      finally
        FreeAndNil(NewFile);
      end;
    finally
      FreeAndNil(OldFile);
    end;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Image1.Picture.LoadFromFile('factory.bmp');
end;

 

TObject

Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!