opAssign and const?

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


On Saturday, May 05, 2012 05:43:43 Era Scarecrow wrote:
> On Saturday, 5 May 2012 at 03:32:06 UTC, Jonathan M Davis wrote:
> > If you've declared an opAssign, I'd be very surprised if _any_
> > assignment worked which didn't work with the opAssign that you
> > declared.  Once you've declared an opAssign, you've taken over
> > the assignment  operator, and you need to define it for all of
> > the types that you want it to work with.
> 
>   So define all four... gotcha...

You need to define enough that you can pass any X to one of them. Generally, 
you probably just need opAssign(const X) and opAssign(const ref X), but since 
you're trying to have more particular semantics about whether resources get 
transferred or not, you may need all four.

> > According to http://dlang.org/function.html:
> > 
> > ---------
> > Func­tions are over­loaded based on how well the
> > ar­gu­ments to a func­tion can match up with the
> > pa­ra­me­ters. The func­tion with the  best match is
> > se­lected. The lev­els of match­ing are:
> > 
> > 1. no match
> > 2. match with im­plicit con­ver­sions
> > 3. match with con­ver­sion to const
> > 4. exact match
> > ---------
> > 
> > It picks opAssign(X) over opAssign(ref const X) with an
> > argument of type X,because opAssign(X) is an exact match (#4)
> > whereas opAssign(ref const X)requires a conversion to const
> > (#3).
> 
>   I guess there's one question left. Where does the struct live?
> If it closes at ending of the scope I believed that meant the
> stack, but then this would be illegal:
> 
> ref X func() {
>    return X(new ubyte[5]); //reference to local variable!
> }
> 
>   If it lives on the heap too rather than the stack, that'd good
> to know. I don't recall it specifying in TDPL, but it would be
> easy enough to assume it does (Coming from C).

That code _should_ be illegal. It's as bad as

X* func()
{
    X x;
    return &x;
}

I think that there's an enhancement request about making it an error like my 
example is, but I can't find it at the moment. Temporaries definitely go on the 
stack.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list