gpt4 book ai didi

string - Delphi 字符串写入时复制

转载 作者:行者123 更新时间:2023-12-03 14:58:41 28 4
gpt4 key购买 nike

我有这样的代码:

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对字符串使用写时复制。但上面的函数为变量、r、s 和结果打印 3 个不同的地址。所以这很令人困惑。内存中是否只有“Hello”字符串的副本?

最佳答案

每当您获取字符串元素的地址时,在编译器看来,这都算作一次写入。就其而言,您现在有了一个指向字符串内部的原始指针,谁知道您打算用它做什么。所以,从它的角度来看,它是安全的。它决定制作该字符串的唯一副本,以便您可以自由地对原始指针执行任何您计划执行的卑鄙行为。

您的代码编译为:

Project2.dpr.13: r := 'Hello';00419EF8 8D45FC           lea eax,[ebp-$04]00419EFB BAA89F4100       mov edx,$00419fa800419F00 E827D2FEFF       call @UStrLAsgProject2.dpr.14: Writeln(NativeInt(PChar(@r[1])));00419F05 8D45FC           lea eax,[ebp-$04]00419F08 E883D3FEFF       call @UniqueStringU00419F0D 8BD0             mov edx,eax00419F0F A18CE64100       mov eax,[$0041e68c]00419F14 E853B2FEFF       call @Write0Long00419F19 E82EB5FEFF       call @WriteLn00419F1E E845A1FEFF       call @_IOTestProject2.dpr.15: s := r;00419F23 8D45F8           lea eax,[ebp-$08]00419F26 8B55FC           mov edx,[ebp-$04]00419F29 E8FED1FEFF       call @UStrLAsgProject2.dpr.16: Writeln(NativeInt(PChar(@s[1])));00419F2E 8D45F8           lea eax,[ebp-$08]00419F31 E85AD3FEFF       call @UniqueStringU00419F36 8BD0             mov edx,eax00419F38 A18CE64100       mov eax,[$0041e68c]00419F3D E82AB2FEFF       call @Write0Long00419F42 E805B5FEFF       call @WriteLn00419F47 E81CA1FEFF       call @_IOTestProject2.dpr.17: Result := r;00419F4C 8BC3             mov eax,ebx00419F4E 8B55FC           mov edx,[ebp-$04]00419F51 E88ED1FEFF       call @UStrAsgProject2.dpr.18: Writeln(NativeInt(PChar(@Result[1])));00419F56 8BC3             mov eax,ebx00419F58 E833D3FEFF       call @UniqueStringU00419F5D 8BD0             mov edx,eax00419F5F A18CE64100       mov eax,[$0041e68c]00419F64 E803B2FEFF       call @Write0Long00419F69 E8DEB4FEFF       call @WriteLn00419F6E E8F5A0FEFF       call @_IOTest

UniqueStringU 的调用正在执行写时复制中的复制。

关于string - Delphi 字符串写入时复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32937538/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com