Deprecating this(this)

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Apr 2 00:44:14 UTC 2018


On Monday, April 02, 2018 00:25:52 Nicholas Wilson via Digitalmars-d wrote:
> On Sunday, 1 April 2018 at 17:08:37 UTC, Andrei Alexandrescu
> wrote:
> > On 4/1/18 10:59 AM, Nicholas Wilson wrote:
> > [...]
> > int[] sneaky;
> > struct A
> > {
> >
> >     private int[] innocent;
> >     this(this)
> >     {
> >
> >         sneaky = innocent;
> >
> >     }
> >
> > }
> > void main()
> > {
> >
> >     immutable a = A([1, 2, 3]);
> >     auto b = a;
> >     sneaky[1] = 42; // oops
> >     import std.stdio;
> >     writeln(a.innocent); // ooooops
> >
> > }
> >
> > Sadly this (and many similar ones) compiles and runs
> > warning-free on today's compiler. We really need to close this
> > loop, like, five years ago.
>
> How much of this class of bug would be eliminated by requiring
> that `this(this)` be pure for assignment to const and immutable
> objects? Arguably this(this) should always be pure in any sane
> program. The only reason I can think of is if you're trying to
> perf the number of copies you're making, but there is compiler
> help for that.

All kinds of things could be done with a postlbit costructor that don't
actually involve copying. These include logging or printing something, and
they could include stuff like reference counting, which may or may not need
access to something external. debug statements would solve some uses cases
but not all. Requiring that this(this) be pure has some of the same issues
that requiring opEquals to be pure or const or whatever has. It makes sense
in _most_ cases, but occasionally, there are good reasons for it not to be -
especially in a systems language.

We have to be _very_ careful about requiring any particular attribute much
of anywhere. Doing so typically causes problems - e.g. those we have with
Object's opEquals, opCmp, toHash, and toString. That decision really needs
to be left up to a particular code base. It's also a big part of why
templates infer attributes. Someone can write their code in such a way that
their code base requires a particular attribute, but in general, language
features shouldn't be requiring any specific attributes, or we'll just be
backing ourselves into another corner.

- Jonathan M Davis



More information about the Digitalmars-d mailing list