DMD 0.177 release

Kevin Bealer kevinbealer at gmail.com
Thu Dec 14 01:41:10 PST 2006


== Quote from Andrei Alexandrescu (See Website For Email)
(SeeWebsiteForEmail at erdani.org)'s article
> Walter Bright wrote:
> > Andrei Alexandrescu (See Website for Email) wrote:
> >
> >> That makes me wonder - if a = b is used without picking up its result
> >> (the usual case), and if opAssign() returns an S, will the compiler
> >> optimize away the extra copy at zero cost?
> >
> >
> > No. The caller and callee don't know about each other.
> >
> >> What I think happens is that the function will take a pointer to the
> >> destination which is zero, so a comparison will be made. But perhaps
> >> the optimizer will take care of eliminating that?
> >
> >
> > You could have a null pointer passed to the return result, but that
> > would entail an extra check on the part of the callee.
> >
> > This is why a lot of C++ code tends to return references instead of values.
> I guess compiling internally two versions, one that returns S and one
> that returns void, might be worth looking into. Because right now user
> code for opAssign() can't be politically correct and efficient at the
> same time.
> Here's a better alternative:
> Require opAssign() to always return void and have the compiler return a
> reference to the left-hand side. That is, transform:
> a = b;
> into:
> (a.opAssign(b), a);
> with the mention that a only gets evaluated once.
> This way assignment _always_ returns its left-hand side and user code
> cannot subvert that behavior. Also the code will be efficient because no
> more spurious copies are being made.
> Andrei

I wonder, are there cases where assignment should not return 'this'?

What I'm thinking of is something like:

class StringExpression {
  ... holds equations between strings
};

class String {
   // wrapper around char[]
   StringExpression opCat(String x);
   StringExpression opCat(StringExpression x);
};

This 'expression-class' stuff is done more commonly with matrices, where the
programmer is trying to to combine multiplies and adds via some optimization rules.

Since C++ at least is flexible (syntax wise at least) on operator inputs and
outputs, I have to wonder if there are really consequences for not following those
expectations here.

Imagine a string expression like this:

a = b ~ (c = d ~ e);

Now if I can do "StringExpression String::opAssign(...)", this could maybe be
rewritten (code not shown...) to result in something like this:

a = b ~ d ~ e;
c = a[b.length..a.length];

Not that this is worth the effort or that the language should do this with
strings, but as a programmer, can I reasonably do this kind of trick with operator
return values or am I just digging a hole for myself?  (I realize that even if
useful it may not be worthwhile.)

Kevin



More information about the Digitalmars-d-announce mailing list