Sign in Join
Wiki copytemporary

FreeAndNil: what changed

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

Title: FreeAndNil

OldNewLine
1+**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]].
2+
3+``` pascal
4+procedure FreeAndNil( var obj );
5+```
6+
7+Example:
8+
9+``` pascal
10+{$mode ObjFPC}
11+uses SysUtils;
12+
13+type
14+ SomeClass = class(TObject)
15+ destructor Destroy; override;
16+ end;
17+
18+destructor SomeClass.Destroy;
19+begin
20+ WriteLn('SomeClass Destructor called');
21+ inherited;
22+end;
23+
24+var
25+ myClass : SomeClass;
26+ myClass2: SomeClass;
27+begin
28+ myClass := SomeClass.Create;
29+ WriteLn('myClass is assigned? ', Assigned(myClass));
30+ myClass2 := SomeClass.Create;
31+ WriteLn('myClass2 is assigned? ', Assigned(myClass2));
32+ myClass.Destroy;
33+ WriteLn('myClass is assigned? ', Assigned(myClass));
34+ FreeAndNil(myClass2);
35+ WriteLn('myClass2 is assigned? ', Assigned(myClass2));
36+ // assigning Nil after destructor is called is the same as
37+ // FreeAndNil
38+ myClass := Nil;
39+ WriteLn('myClass is assigned? ', Assigned(myClass));
40+end.
41+```
42+
43+**Output:**
44+
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`
52+
53+---
54+*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).*
55+Category: FPC

Back to history