Problem with insertBack
ag0aep6g via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jun 3 08:03:45 PDT 2016
On 06/03/2016 04:34 PM, John Nixon wrote:
> import std.stdio;
> import std.container;
> struct CS{
> char[] t;
> CS dup()const{
> CS cs;
> cs.t = this.t.dup;
> return cs;}
> };
Aside: No semicolon after struct declarations in D.
> void main(){
> Array!CS cs_array = make!(Array!CS)();
cs_array stores its data somewhere on the heap.
> CS cs;
cs is on the stack.
> cs.t = "bb".dup;
But cs.t's data is on the heap, like cs_array's. cs.t contains a pointer
to it.
> cs_array.insertBack(cs);
This copies cs to cs_array's heap. The pointer in cs.t is being copied,
but the data that it points to is not being copied. So cs.t and
cs_array[0].t contain two distinct but equal pointers now. Since they're
equal, they refer to the same data.
> write("cs_array = ");foreach(i2;cs_array)write(i2);writeln("");
> cs.t[0] = ("a".dup)[0];//this changes cs_array!
This is expected since cs.t and cs_array[0].t point to the same
location. A change to the data through one of them is visible to the other.
> write("cs_array = ");foreach(i2;cs_array)write(i2);writeln("");
> cs.t = "c".dup;//but this does not
Here you're not writing through the pointer in cs.t, but rather you're
assigning a whole new one. Since the pointers in cs.t and cs_array[0].t
are independent of each other, they now point to different locations,
with different data.
> write("cs_array = ");foreach(i2;cs_array)write(i2);writeln("");
> return;}
More information about the Digitalmars-d-learn
mailing list