h <--+
v +- before free
---[ttttNNNNNNNNNN]--- |
1234My house <--+
h (now points nowhere) <--+
+- after free
---------------------- | (note, memory might still
xx34My house <--+ contain some data)
procedure OpenTheFrontDoorOfANewHouse;
var
h: THouse;
begin
h := THouse.Create('My house');
h.OpenFrontDoor;
// uh-oh, no .Free here, where does the address go?
end;
在这个方法执行之后,我们的变量中没有房子的地址存在,但是房子仍然在那里。
内存布局:
h <--+
v +- before losing pointer
---[ttttNNNNNNNNNN]--- |
1234My house <--+
h (now points nowhere) <--+
+- after losing pointer
---[ttttNNNNNNNNNN]--- |
1234My house <--+
正如你所看到的,旧的数据在内存中是完整的,而不是
被内存分配器重用。分配器会跟踪它
内存区域已被使用,并且不会重用它们,除非您
自由。< / p >
var
h1, h2: THouse;
begin
h1 := THouse.Create('My house');
h2 := h1; // copies the address, not the house
...
h1.Free;
h1 := nil;
h2.OpenFrontDoor; // uh-oh, what happened to our house?
var
h1, h2: THouse;
begin
h1 := THouse.Create('My house');
h2 := THouse.Create('My other house somewhere');
^-----------------------^
longer than 10 characters
0123456789 <-- 10 characters
第一次分配后的内存布局:
h1
v
-----------------------[ttttNNNNNNNNNN]
5678My house
第二次分配后的内存布局:
h2 h1
v v
---[ttttNNNNNNNNNN]----[ttttNNNNNNNNNN]
1234My other house somewhereouse
^---+--^
|
+- overwritten
var
h1, h2: THouse;
h: THouse;
begin
h1 := THouse.Create('Home');
h2 := THouse.Create('Cabin');
h1.NextHouse := h2;
...
h := h1;
while h <> nil do
begin
h.LockAllDoors;
h.CloseAllWindows;
h := h.NextHouse;
end;
内存布局(在对象中添加NextHouse作为链接,用
下图中的四个LLLL):
h1 h2
v v
---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL]
1234Home + 5678Cabin +
| ^ |
+--------+ * (no link)