Struct should be invalid after move

Manu turkeyman at gmail.com
Tue Nov 27 19:51:12 UTC 2018


On Tue, Nov 27, 2018 at 1:08 AM Stanislav Blinov via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
>
> On Tuesday, 27 November 2018 at 08:37:32 UTC, Nicholas Wilson
> wrote:
> > On Tuesday, 27 November 2018 at 08:00:22 UTC, Sebastiaan Koppe
> > wrote:
> >> I have a non-copyable struct and I really want a compiler
> >> error whenever I access it after it has been moved.
> >>
> >> ---
> >> struct Handle {
> >>     ...
> >>     @disable this(this);
> >>     ...
> >> }
> >>
> >> void main() {
> >>     import std.algorithm : move;
> >>     auto handle = getOne();
> >>     auto second = handle.move;  /// line 14
> >>     auto third = handle.move;    ///  <- compiler error,
> >> variable handle is invalid after line 14
> >> }
> >> ---
> >>
> >> I believe this would prevent some nasty bugs when dealing with
> >> these structs.
> >>
> >> What do you think?
> >
> > we need an `@invalidate`s attribute for that, would apply to
> > pointers passed to free etc. Probably would need a DIP though.
> > I like it.
>
> Yeah, that could be an awesome addition. However, it's not as
> simple, because this should be legal too:
>
> ```
> auto handle = getOne();
> auto second = handle.move; // `handle` becomes invalid
> // ...
> handle = getOne(); // `handle` is valid again
> ```

The language goes to great effort to return everything to it's `init`
state after being moved or destroyed. The whole point of that is to
cover the cases you are concerned about here.
If it was invalid to access a thing after it's moved (or after
destruction), then there's no reason for any of the work that resets
thing to their `init` to happen... that's quite a different set of
language semantics.


More information about the Digitalmars-d mailing list