opAssign and const?

Era Scarecrow rtcvb32 at yahoo.com
Fri May 4 13:35:54 PDT 2012


On Friday, 4 May 2012 at 12:42:54 UTC, Steven Schveighoffer wrote:
> I don't think it will make a copy of a temporary even if it's  
> cast to const.  I think marking the non-ref version as const  
> will solve the problem how you wish (as long as the argument  
> really *isn't* modified inside that function).

  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.

import std.stdio;
import std.conv;

struct X {
   int x;
   int y;

   this (int x1, int y1) {
     x = x1; y = y1;
   }

   ref X opAssign(const X x2) {
     writeln("from temporary?");
     x=x2.x;
     y=x2.y;
     return this;
   }

   ref X opAssign(const ref X x2) {
     writeln("copy specific values?");
     x=x2.x;
     return this;
   }
}

//from temporary
X fn() {
   return X(1,2);
}

void main()
{
   X x = X(3,4);
   X y = X(5,6);

   x = y;    // 5,4 or 5,6?
   writeln("Should selectively copy (5,4) - ", to!string(x));

   x = fn();  // 1,2
   writeln("should overwrite all (1,2)- ", to!string(x));
}


More information about the Digitalmars-d-learn mailing list