Error in assignment to 'this' inside constructor

evilrat evilrat666 at gmail.com
Sat May 11 20:32:43 PDT 2013


On Saturday, 11 May 2013 at 14:34:41 UTC, TommiT wrote:
> I'm trying to assign (or simply bit-copy) over 'this' inside a 
> constructor. There's an error when compile-time constructing 
> the object. Is this a bug in DMD (2.062) ?
>
> module main;
>
> struct Test
> {
>     enum Test t = Test(1);
>     int v;
>
>     this(int)
>     {
>         v = 123;
>     }
>
>     this(int, int)
>     {
>         this = t;
>     }
> }
>
> void main()
> {
>     Test t1 = Test(11, 22);
>     writeln(t1.v); // Prints: 123
>
>     enum t2 = Test(11, 22); // Error:
>     // CTFE internal error: unsupported assignment this = 
> Test(123)
> }

what? structs has value semantics, every time you assign a struct 
to variable it assign its copy.

you also don't have to have constructor for structs, it 
initializes it fields in left-to-right order or so.


struct A
{	
int x;
}

void main()
{
A s1 = A(1);
A s2 = A(2);
A s3;

s3 = s2;
s2.x = 5;

assert(s3.x == 2);
assert(s2.x == 5);
}


More information about the Digitalmars-d-learn mailing list