多个字符串变量真的可以引用相同的数据吗?
根据网上的信息我发现以下两个变量 指向内存中的同一位置。
任何人都可以提出一个代码示例来证明它实际上是正确的(例如,通过更改第一个变量中的一个字母,并看到此更改从第二个变量中可见)?
procedure TForm1.Button1Click(Sender: TObject);
var
a, b: String;
begin
a := 'Test';
b := a;
showmessage (a);
showmessage (b);
end;
According to the information in the internet I found out that two following variables
point to the same place in memory.
Could anyone propose a code example to demonstrate that in fact it is true (e.g. by changing one of the letter in the 1st variable and see that this change is visible from the second variable)?
procedure TForm1.Button1Click(Sender: TObject);
var
a, b: String;
begin
a := 'Test';
b := a;
showmessage (a);
showmessage (b);
end;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
结果是
True
,所以是的,a
和b
指向相同的数据。但请注意,它
应该显示
False
。另外,请注意,
还显示
False
,因为a
和b
是不同字符串(指针)变量,因此内存中某个地方(@a
)是a
数据的地址,其他地方(@b
)是b
的数据。第一个示例表明,内存中的这两个位置包含相同的地址,即a
和b
包含相同的数据。The result is
True
, so yes,a
andb
point to the same data.Notice, however, that
displays
False
, as it should be.In addition, notice that
also displays
False
, becausea
andb
are different string (pointer) variables, so at some place in memory (@a
) is the address of the data ofa
, and somewhere else (@b
) is the address of the data ofb
. The first example shows that these two places in memory contain the same address, that is, thata
andb
contain the same data.通常,Delphi 对字符串使用“写时复制”语义,因此您需要一种黑客技术来实现这一目的,例如:
Normally Delphi use 'copy-on-write' semantics for strings, so you need a kind of hacking to do the trick, for example:
你的问题对我来说不是很清楚。
如果你这样做:
我想你会看到它......
Your question is not very clear for me.
If you do :
I think you will see it...
OK,这段代码可能会更清楚
OK may be more clear with this code