opAssign and const?

Jonathan M Davis jmdavisProg at gmx.com
Fri May 4 19:20:45 PDT 2012


On Saturday, May 05, 2012 01:18:13 Era Scarecrow wrote:
> On Friday, 4 May 2012 at 21:29:14 UTC, Steven Schveighoffer wrote:
> > On Fri, 04 May 2012 17:26:02 -0400, Era Scarecrow
> > 
> >> On Friday, 4 May 2012 at 21:12:55 UTC, Steven Schveighoffer
> >> 
> >> wrote:
> >>> y[] = x2.y[];
> >>> // as you did below
> >> 
> >> That may deal with the language requirements, but the ideal
> >> was to take over the temporary; If not the ref would copy the
> >> contents. I wonder if I will need to have 2 copies of each
> >> opAssign to satisfy everything.
> > 
> > OK, I see what you are trying to do.  I'll have to think about
> > it some more.  I'm very concerned that you could potentially
> > end up calling this function with an lvalue, which would make
> > this a disastrous strategy.
> 
>   Well let's see if we can recap it into perspective so we're on
> the same Page. I'm trying to make a struct that on assignment
> will copy it's contents.
> 
>   On opAssign In both cases the mutable and const/immutable rvalue
> will copy it's contents. If it's a temporary (which is always
> returned as mutable) I want to take it over rather than copy the
> contents. The contents are likely referenced elsewhere already.

As I understand it, you don't need to do _anything_ special to avoid having a 
temporary copied when passed to your function. Because it's a temporary, it 
should be moved into the function parameter, not copied. No postblit or 
opAssign will be executed. It's only when it's _not_ a temporary that a copy 
will be made. And even in _that_ case, it should be a move if that function 
call is the last place that the variable is used.

So, I believe that you're trying to avoid copies that will never happen 
anyway. They would if you were dealing with C++ - particularly C++98 - but not 
in D (C++11 fixes the problem via move constructors).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list