Why it doesn't compile in D 2.0?

Simen kjaeraas simen.kjaras at gmail.com
Sat Jan 16 04:26:21 PST 2010


aarti_pl <aarti at interia.pl> wrote:

>
> class Test {
>      string t1 = "test";		//Ok!
>      char[] t2 = "test".dup;	//Compile error
> }
>
> void main(char[][] args) {
> }
>
> Error:
> hello.d(3): Error: cannot evaluate _adDupT((&  
> D12TypeInfo_Aya6__initZ),"test") at compile time
> hello.d(3): Error: cannot evaluate _adDupT((&  
> D12TypeInfo_Aya6__initZ),"test") at compile time
>
> Is there workaround?

Constant strings are saved in the static data segment of the executable, so
the .dup call would need to be executed at runtime. In other words, what
this would do is cast const to mutable.

If this did compile, changing the contents of t2 would change those  
contents
for all instances of Test, which I assume is not your intention.

As for the workaround, write a constructor:

class Test {
   string t1 = "test";
   string t2;

   this( ) {
     t2 = "test".dup;
   }
}

-- 
Simen


More information about the Digitalmars-d-learn mailing list