Warning on self assignment

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Apr 25 07:31:25 UTC 2018


On Wednesday, April 25, 2018 02:23:04 Mike Franklin via Digitalmars-d-learn 
wrote:
> On Wednesday, 25 April 2018 at 01:08:46 UTC, Arun Chandrasekaran
>
> wrote:
> > So I was telling my colleague that D would warn on self
> > assignment, but found that I was wrong.
> >
> > https://run.dlang.io/is/HLhtek
> >
> > ```
> > module a;
> >
> > import std.stdio;
> >
> > void main() {
> >
> >     string a;
> >     a = a;          // Can the compiler warn at this line that
> >
> > there is no effect?
> >
> >     writeln(a);
> >     return;
> >
> > }
> > ```
>
> Are people using self assignment of structs as a way of
> force-running the postblit?  Is there a valid use case for that?

I would be _very_ surprised if there were a valid reason to do that. That
being said, it's not necessarily true that

a = a;

has no effect. In the case of string that's basically true, but if the type
has a postblit constructor, then it definitely can have an effect (e.g. it
allocates memory or prints out that the object was copied). I don't think
that it's at all likely to have a desirable effect, and I would expect for
it to be fine for

a = a;

to be deprecated and then turned into an error on the grounds that there
isn't a reasonable reason to do it and is probably a bug - especially in
cases such as

this(A a, B b)
{
    a = a;
    b = b;
}

but it's likely untrue in the general case to say that that statement has no
effect.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list