dynamic arrays of immutable question: Are the elements actually mutable

Jonathan M Davis jmdavisProg at gmx.com
Wed Jan 9 04:37:13 PST 2013


On Wednesday, January 09, 2013 13:29:43 monarch_dodra wrote:
> I was investigating the inner working of appender, and I'm not
> 100% sure what it is doing with arrays of immutables is
> completely kosher.
> 
> However, I'm not 100% how arrays of immutables work.
> 
> In particular, since dynamic arrays can be appended to, by
> design, the elements can be mutated, right?
> I mean, take this program:
> //----
>      immutable(int)[] arr = [1, 2];
>      // data in memory [1, 2, 0, 0, 0, ...
> 
>      arr ~= 3;
>      // data in memory [1, 2, 3, 0, 0, ...
> 
>      arr ~= 4;
>      // data in memory [1, 2, 3, 4, 0, ...
> //----
> I don't actually know if the data is 0 initilized, but I figure
> it is irrelevent: The point is that the data *has* to be mutated
> for appending, so the data can't be immutable.
> 
> So my question is:
> If I by-pass compiler protections via casting, is modifying the
> elements of a dynamic array* of immutables actually defined
> behavior ?
> 
> * Assuming GC allocated dynamic array, and not slice of static
> immutable array, for example.
> 
> http://dpaste.dzfl.pl/41eeeacf

When you append to array, the elements being added are in untyped memory. So, 
no mutation of immutable anything is going on at all.

I don't know what Appender is doing, but casting away immutable and mutating 
anything is undefined behavior. However, if you _know_ that the data is 
actually mutable, then you can get away with it. It's still technically 
undefined behavior though. Pretty much the only place that it would make sense 
to do that that I can think of is with std.concurrency, but again, I don't 
know what Appender is doing.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list