Error in assignment to 'this' inside constructor
TommiT
tommitissari at hotmail.com
Sun May 12 08:04:13 PDT 2013
On Sunday, 12 May 2013 at 11:27:50 UTC, evilrat wrote:
> oh right,
> struct A {
> this(this) { copy referenced mem here}
> }
>
> or
> struct A {
> ref A opAssign(ref const A other) { this = other; return this; }
> }
>
> so if you have fields that should be fully copied like array
> this is the place to do it, otherwise there is a reference
> arguments, if both is no go for you then this behavior would
> make more trouble than benefits and thats.
>
> so gather all up here are some little example
> ----
>
> struct A
> {
> int x;
> int[] array;
>
> this(int x) { this.x = x; array ~= x; }
> this(this) { array = array.dup; }
>
> ref A opAssign(ref const A other) { this = other; return this;
> }
> }
>
> void main()
> {
> A a1 = A(1);
> A a2 = A(2);
> A a3 = a2;
>
> a2.x = 5;
>
> assert(a2.x == 5);
> assert(a2.array[0] == 5);
>
> assert(a3.x == 2);
> assert(a3.array[0] == 2);
>
> assert(a2.array.length == 1);
> assert(a3.array.length == 1);
>
> }
You're assigning to 'this', i.e. calling assignment operator,
inside the assignment operator. That results in an infinite
recursion. That code never calls the assignment operator though,
but try a1 = a2 for example and that should crash.
More information about the Digitalmars-d-learn
mailing list