Problem with insertBack

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 3 07:55:11 PDT 2016


On 6/3/16 10:34 AM, John Nixon wrote:
> I recently came across another problem with my program in D, found a
> minimal program showing it, and experimented a little with it as follows:
>
> import std.stdio;
> import std.container;
> struct CS{
>   char[] t;
>   CS dup()const{
>     CS cs;
>     cs.t = this.t.dup;
>     return cs;}
> };
> void main(){
>   Array!CS cs_array = make!(Array!CS)();
>   CS cs;
>   cs.t = "bb".dup;
>   cs_array.insertBack(cs);
>   write("cs_array = ");foreach(i2;cs_array)write(i2);writeln("");
>   cs.t[0] = ("a".dup)[0];//this changes cs_array!

You have inside your CS struct a pointer to a heap array. Then you 
change the heap array later. The CS element you put into the cs_array 
still points at the same piece of memory.

Perhaps you meant to insert cs.dup?

>   write("cs_array = ");foreach(i2;cs_array)write(i2);writeln("");
>   cs.t = "c".dup;//but this does not

Right, because the cs stored on the stack is now pointing at a different 
heap-allocated array

>   write("cs_array = ");foreach(i2;cs_array)write(i2);writeln("");
>   return;}
>
> The first assignment to cs.t[0] changes cs_array as indicated, but the
> second to cs.t does not. Also if these two assignments are reversed,
> neither affects cs_array. What could be the explanation of this?

Right, because if the stack is pointing at a different array than the 
cs_array[0], then altering won't affect cs_array[0].

-Steve


More information about the Digitalmars-d-learn mailing list