根据互联网上的信息,我发现以下两个变量指向内存中的同一位置。
任何人都可以提出一个代码示例来证明它实际上是正确的(例如,通过更改第一个变量中的一个字母并看到此更改从第二个变量中可见)?
procedure TForm1.Button1Click(Sender: TObject);
var
a, b: String;
begin
a := 'Test';
b := a;
showmessage (a);
showmessage (b);
end;
根据互联网上的信息,我发现以下两个变量指向内存中的同一位置。
任何人都可以提出一个代码示例来证明它实际上是正确的(例如,通过更改第一个变量中的一个字母并看到此更改从第二个变量中可见)?
procedure TForm1.Button1Click(Sender: TObject);
var
a, b: String;
begin
a := 'Test';
b := a;
showmessage (a);
showmessage (b);
end;
procedure TForm4.FormCreate(Sender: TObject);
var
a, b: string;
begin
a := 'Test';
b := a;
ShowMessage(BoolToStr(pointer(a) = pointer(b), true));
end;
结果是True
,所以是的,a
并且b
指向相同的数据。
但是请注意,
procedure TForm4.FormCreate(Sender: TObject);
var
a, b: string;
begin
a := 'Test';
b := a;
b := 'Test2';
ShowMessage(BoolToStr(pointer(a) = pointer(b), true));
end;
显示False
,因为它应该是。
此外,请注意
procedure TForm4.FormCreate(Sender: TObject);
var
a, b: string;
begin
a := 'Test';
b := a;
ShowMessage(BoolToStr(@a = @b, true));
end;
也显示False
, 因为a
和b
是不同的字符串(指针)变量,所以在内存@a
中的某个地方 ( ) 是 的数据的地址,a
而在其他地方 ( @b
) 是 的数据的地址b
。a
第一个例子表明内存中的这两个位置包含相同的地址,即b
包含相同的数据。
通常,Delphi 对字符串使用“写时复制”语义,因此您需要一种黑客技术来做到这一点,例如:
procedure TForm13.Button1Click(Sender: TObject);
const
Test: string = '12345';
var
S1, S2: string;
P: PChar;
begin
SetString(S1, PChar(Test), 5);
// we need to copy '12345' string from readonly memory to heap
S2:= S1;
// Now both S1 and S2 points to the same memory
P:= Pointer(S1);
P^:= 'A';
ShowMessage(S2); // 'A2345'
end;
var
a, b: string;
begin
a := 'Test';
a := a + '!'; // added after Rob's comment below,
// makes sure a points to an allocation on the heap
b := a;
PChar(b)[3] := 'T';
ShowMessage(a); //--> TesT!
end;
你的问题对我来说不是很清楚。如果你这样做:
begin
a := 'Test';
b := a;
a := a+'HH';
showmessage (a);
showmessage (b);
end;
我想你会看到的...
使用此代码可能会更清楚
procedure TForm1.FormCreate(Sender: TObject);
var
a, b , s : string;
p : pointer;
begin
a := 'Test';
b := a;
// we see the 2 diff. var pointing on the same adress
s := Format('%p -> %p / %p -> %p', [@pointer(a),pointer(a),@pointer(b),pointer(b)] );
ShowMessage( 'first : '+s);
// we see the 2 diff. var pointing on different adresses
a := 'Test2';
s := Format('%p -> %p / %p -> %p', [@pointer(a),pointer(a),@pointer(b),pointer(b)] );
ShowMessage( 'second : '+s);
end;