Here is the rather artificial code sample. What is the problem?
program TestFreeAndNil; {$APPTYPE CONSOLE} uses System.SysUtils; type TApartment = class private FKitchen : TObject; FBedRoom : TObject; FSalon : TObject; protected function GetSalon : TObject; public property Kitchen : TObject read FKitchen write FKitchen; property BedRoom : TObject read FBedRoom write FBedRoom; property Salon : TObject read GetSalon write FSalon; end; function TApartment.GetSalon : TObject; begin Result := FSalon; end; var Apartment : TApartment; begin Apartment := TApartment.Create; Apartment.Kitchen := TObject.Create; Apartment.BedRoom := TObject.Create; Apartment.Salon := TObject.Create; // .. more code here FreeAndNil(Apartment.Kitchen); FreeAndNil(Apartment.BedRoom); FreeAndNil(Apartment.Salon); // .. more code following involving // Apartment and its fields end.FreeAndNil (System.SysUtils) is a convenient method to destroy an object and set it to nil. Of course it is better to just call Free, if the object anyway is going out of scope. But if you need to later use the object again, it can be useful to call FreeAndNil.
But there is a big problem with the above code:
First two calls to FreeAndNil work as expected. The object is destroyed and set to nil. But the last call to FreeAndNil(Apartment.Salon) gives that Apartment.Salon will not be set to nil! The object itself however is destroyed. If you want to check this, just compile the code and run the debugger.
If you call FreeAndNil for a property, make sure that the property has not got a get-function.
But the good news is that in the upcoming May updates of Pascal Analyzer and Pascal Expert, the WARN56-Parameter to FreeAndNil is not an object report section, will report also these situations.
Can you see the Delphi coding error? (Part 14) Can you see the Delphi coding error? (Part 13) Can you see the Delphi coding error? (Part 12) Can you see the Delphi coding error? (Part 11) Can you see the Delphi coding error? (Part 10) Can you see the Delphi coding error? (Part 9) Can you see the Delphi coding problem? (Part 8) Can you see the Delphi coding error? (Part 7) Can you see the Delphi coding error? (Part 6) Can you see the Delphi coding error? (Part 5) Can you see the Delphi coding error? (Part 4) Can you see the Delphi coding error? (Part 3) Can you see the Delphi coding error? (Part 2) Can you see the Delphi coding error? (Part 1)