Doubt about Struct and members
matheus
matheus at gmail.com
Mon Jan 8 17:28:50 UTC 2024
Hi,
I was doing some tests and this code:
import std;
struct S{
string[] s = ["ABC"];
int i = 123;
}
void foo(bool b, string str){
S t1;
writeln("t1.s: ", t1.s, ", t1.s.ptr: ", t1.s.ptr, " t1.i: ",
t1.i);
if(b){
t1.s[0] = str;
}else{
t1.s = [str];
}
t1.i = 456;
S t2;
writeln("t1.s: ", t1.s, ", t1.s.ptr: ", t1.s.ptr, " t1.i: ",
t1.i);
writeln("t2.s: ", t2.s, ", t2.s.ptr: ", t2.s.ptr, " t2.i: ",
t2.i);
writeln("");
}
void main(){
foo(false, "DEF");
foo(true, "DEF");
foo(false, "XYZ");
}
Outputs:
t1.s: ["ABC"], t1.s.ptr: 56421C6D7010 t1.i: 123
t1.s: ["DEF"], t1.s.ptr: 7EFC725E6000 t1.i: 456
t2.s: ["ABC"], t2.s.ptr: 56421C6D7010 t2.i: 123
t1.s: ["ABC"], t1.s.ptr: 56421C6D7010 t1.i: 123
t1.s: ["DEF"], t1.s.ptr: 56421C6D7010 t1.i: 456
t2.s: ["DEF"], t2.s.ptr: 56421C6D7010 t2.i: 123
t1.s: ["DEF"], t1.s.ptr: 56421C6D7010 t1.i: 123
t1.s: ["XYZ"], t1.s.ptr: 7EFC725E6020 t1.i: 456
t2.s: ["DEF"], t2.s.ptr: 56421C6D7010 t2.i: 123
As you can see:
t1.s = [str];
Just changed generated a new address only for t1.s, on the other
hand:
t1.s[0] = str;
Changed the value pointed by S.s entirely (The other "instance"
t2 since points to the same address now has the new value too).
Is this intended?
Matheus.
More information about the Digitalmars-d-learn
mailing list