opAssign and const?

Steven Schveighoffer schveiguy at yahoo.com
Fri May 4 14:12:52 PDT 2012


On Fri, 04 May 2012 16:47:07 -0400, Era Scarecrow <rtcvb32 at yahoo.com>  
wrote:

> On Friday, 4 May 2012 at 20:35:57 UTC, Era Scarecrow wrote:
>
>>  Well the result seems to be true enough.. It also seems to work if  
>> both are const. Why didn't I consider that before? Maybe it should be  
>> noted in the next TDPL book.
>
>   As I look at my code I realize why now. Pointers and arrays... that's  
> why...
>
> test.d(16): Error: cannot implicitly convert expression (x2.y) of type  
> const(int[]) to int[]
>
>   Which is why I was trying to suggest the ref was const since I wasn't  
> modifying and could ensure it (just copying between buffers) but the  
> temporary I'm taking over.. So that doesn't work now.
>
>   This means I'll likely need 2 copies of the ref; 1 const and 1  
> non-const.
>
> import std.stdio;
> import std.conv;
>
> struct X {
>    int x;
>    int[] y;
>
>    this (int x1, int y1) {
>      x = x1; y ~= y1;
>    }
>
>    //const here won't work.
>    ref X opAssign(const X x2) {
>      writeln("from temporary?");
>      x=x2.x;
>      y=x2.y; //breaks here

y[] = x2.y[];
// as you did below

>      return this;
>    }
>
>    ref X opAssign(ref const X x2) {
>      writeln("copy specific values?");
>      x=x2.x;
> 	y[]=x2.y[];
>      return this;
>    }
> }
>
> X fn() {
>    return X(1,2);
> }
>
> void main()
> {
>    X x = X(3,4);
>    X y = X(5,6);
>
>    x = y;
>    writeln("Should selectively copy (ref)- ", to!string(x));
>
>    x = fn();
>    writeln("should overwrite all - ", to!string(x));
> }

btw, are you sure the lengths will always be identical?  Otherwise, you  
may want to do y.length = x2.y.length first.

-Steve


More information about the Digitalmars-d-learn mailing list