Sign in Join
Wiki copytemporary

FreeAndNil: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11**FreeAndNil** is a procedure defined in the [[SysUtils unit]] of the Free Pascal [[RTL|Runtime Library]]. It calls an object's destructor (via TObject.Free) and also sets the object variable (which is a reference to heap memory created by a constructor call) to nil. If you just call an object's destructor, [[Assigned]] will still return [[True]] for the object variable. But after calling FreeAndNil, [[Assigned]] will return [[False]] for the object variable. While the procedure has an *untyped parameter*, it is only for use with object references - that is variables that are instances of a [[Class]].
22
33``` pascal
44procedure FreeAndNil( var obj );
55```
66
77Example:
88
99``` pascal
1010{$mode ObjFPC}
1111uses SysUtils;
1212
1313type
1414 SomeClass = class(TObject)
1515 destructor Destroy; override;
1616 end;
1717
1818destructor SomeClass.Destroy;
1919begin
2020 WriteLn('SomeClass Destructor called');
2121 inherited;
2222end;
2323
2424var
2525 myClass : SomeClass;
2626 myClass2: SomeClass;
2727begin
2828 myClass := SomeClass.Create;
2929 WriteLn('myClass is assigned? ', Assigned(myClass));
3030 myClass2 := SomeClass.Create;
3131 WriteLn('myClass2 is assigned? ', Assigned(myClass2));
3232 myClass.Destroy;
3333 WriteLn('myClass is assigned? ', Assigned(myClass));
3434 FreeAndNil(myClass2);
3535 WriteLn('myClass2 is assigned? ', Assigned(myClass2));
3636 // assigning Nil after destructor is called is the same as
3737 // FreeAndNil
3838 myClass := Nil;
3939 WriteLn('myClass is assigned? ', Assigned(myClass));
4040end.
4141```
4242
4343**Output:**
4444
45-` myClass is assigned? TRUE  `\
46-` myClass2 is assigned? TRUE`\
47-` SomeClass Destructor called`\
48-` myClass is assigned? TRUE`\
49-` SomeClass Destructor called`\
50-` myClass2 is assigned? FALSE`\
51-` myClass is assigned? FALSE`
45+```text
46+ myClass is assigned? TRUE
47+ myClass2 is assigned? TRUE
48+ SomeClass Destructor called
49+ myClass is assigned? TRUE
50+ SomeClass Destructor called
51+ myClass2 is assigned? FALSE
52+ myClass is assigned? FALSE
53+```
5254
5355---
5456*From the Free Pascal wiki, page "FreeAndNil", as it stood on 2020-12-27 after a change by Jouborg, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
5557Category: FPC

Back to history