www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Copying to an immutable array in a costructor

reply "bearophile" <bearophileHUGS lycos.com> writes:
This shows a limitation of the D type system:


import std.algorithm: copy;
immutable int[2] data;
static this() {
     foreach (i, x; [10, 20]) data[i] = x; // OK
     data[] = [10, 20]; // OK
     [10, 20].copy(data[]); // Error.
}
void main() {}


Bye,
bearophile
Oct 24 2013
next sibling parent reply Jonathan M Davis <jmdavisProg gmx.com> writes:
On Thursday, October 24, 2013 09:02:24 bearophile wrote:
 This shows a limitation of the D type system:
 
 
 import std.algorithm: copy;
 immutable int[2] data;
 static this() {
      foreach (i, x; [10, 20]) data[i] = x; // OK
      data[] = [10, 20]; // OK
      [10, 20].copy(data[]); // Error.
 }
 void main() {}
It's a compiler bug. immutable data should not be initialized more than once. - Jonathan M Davis
Oct 24 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jonathan M Davis:

 It's a compiler bug. immutable data should not be initialized 
 more than once.
My point was another one, regarding this refused code: import std.algorithm: copy; immutable int[2] data; static this() { [10, 20].copy(data[]); // Error. } void main() {} Bye, bearophile
Oct 24 2013
parent "Maxim Fomin" <maxim maxim-fomin.ru> writes:
On Thursday, 24 October 2013 at 10:58:30 UTC, bearophile wrote:
 Jonathan M Davis:

 It's a compiler bug. immutable data should not be initialized 
 more than once.
My point was another one, regarding this refused code: import std.algorithm: copy; immutable int[2] data; static this() { [10, 20].copy(data[]); // Error. } void main() {} Bye, bearophile
Reduced: immutable int[] data; void foo(int[] data) {} static this() { foo(data); }
Oct 24 2013
prev sibling parent "Maxim Fomin" <maxim maxim-fomin.ru> writes:
On Thursday, 24 October 2013 at 07:02:25 UTC, bearophile wrote:
 This shows a limitation of the D type system:


 import std.algorithm: copy;
 immutable int[2] data;
 static this() {
     foreach (i, x; [10, 20]) data[i] = x; // OK
     data[] = [10, 20]; // OK
     [10, 20].copy(data[]); // Error.
 }
 void main() {}


 Bye,
 bearophile
Because control flow check for immutable data is almost absent. I don't know any situation where are such checks (except constructors). There is similar issue with respect to initializsing immutable member field in struct constructor. There is issue in bugzilla filed for it (it looks like it will be fixed), where Andrei proposed a concept of cooked object, basically implying control flow for initializaing immutable members. I think that the code you posted as an additional case for the issue.
Oct 24 2013