Delphi Copy-on-Write for String

时间:2015-10-04 19:32:47

标签: string delphi

我有这样的代码:

function Test: string;
var
   r, s: string;
begin
   r := 'Hello';
   Writeln(NativeInt(PChar(@r[1])));
   s := r;
   Writeln(NativeInt(PChar(@s[1])));
   Result := r;
   Writeln(NativeInt(PChar(@Result[1])));
end;

人们说delphi对字符串使用copy-on-write。但上面的函数为变量,r,s和Result打印3个不同的地址。所以这很令人困惑..内存中只有'Hello'字符串的副本吗?

1 个答案:

答案 0 :(得分:9)

每当你获取字符串元素的地址时,在编译器的眼中就算作 write 。就它而言,你现在有一个指向字符串内部的原始指针,谁知道你打算用它做什么。因此,从它的角度来看,它起到了安全作用。它决定制作一个字符串的唯一副本,这样你就可以自由地做你计划用你的原始指针做的卑鄙行为。

您编写的代码:

Project2.dpr.13: r := 'Hello';
00419EF8 8D45FC           lea eax,[ebp-$04]
00419EFB BAA89F4100       mov edx,$00419fa8
00419F00 E827D2FEFF       call @UStrLAsg
Project2.dpr.14: Writeln(NativeInt(PChar(@r[1])));
00419F05 8D45FC           lea eax,[ebp-$04]
00419F08 E883D3FEFF       call @UniqueStringU
00419F0D 8BD0             mov edx,eax
00419F0F A18CE64100       mov eax,[$0041e68c]
00419F14 E853B2FEFF       call @Write0Long
00419F19 E82EB5FEFF       call @WriteLn
00419F1E E845A1FEFF       call @_IOTest
Project2.dpr.15: s := r;
00419F23 8D45F8           lea eax,[ebp-$08]
00419F26 8B55FC           mov edx,[ebp-$04]
00419F29 E8FED1FEFF       call @UStrLAsg
Project2.dpr.16: Writeln(NativeInt(PChar(@s[1])));
00419F2E 8D45F8           lea eax,[ebp-$08]
00419F31 E85AD3FEFF       call @UniqueStringU
00419F36 8BD0             mov edx,eax
00419F38 A18CE64100       mov eax,[$0041e68c]
00419F3D E82AB2FEFF       call @Write0Long
00419F42 E805B5FEFF       call @WriteLn
00419F47 E81CA1FEFF       call @_IOTest
Project2.dpr.17: Result := r;
00419F4C 8BC3             mov eax,ebx
00419F4E 8B55FC           mov edx,[ebp-$04]
00419F51 E88ED1FEFF       call @UStrAsg
Project2.dpr.18: Writeln(NativeInt(PChar(@Result[1])));
00419F56 8BC3             mov eax,ebx
00419F58 E833D3FEFF       call @UniqueStringU
00419F5D 8BD0             mov edx,eax
00419F5F A18CE64100       mov eax,[$0041e68c]
00419F64 E803B2FEFF       call @Write0Long
00419F69 E8DEB4FEFF       call @WriteLn
00419F6E E8F5A0FEFF       call @_IOTest

UniqueStringU的调用正在写入时写入副本。