[Issue 16131] A struct is being copied unnecessarily when initialized

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Tue Jun 7 23:19:05 PDT 2016


https://issues.dlang.org/show_bug.cgi?id=16131

Eyal <eyal at weka.io> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|RESOLVED                    |REOPENED
         Resolution|INVALID                     |---

--- Comment #3 from Eyal <eyal at weka.io> ---
Perhaps I can illustrate that there is an actual issue with a more convincing
example (and more similar to the actual problem I experienced):

import core.thread : Fiber;
import std.stdio : writeln;

struct Foo {
    int x;
    Fiber fib;
    @disable this(this);
    this(int x) {
        this.x = x;
        fib = new Fiber(&run);
    }
    void run() {
        writeln("Hello from: ", x);
    }
}

void main() {
    Foo[10] foos; // OR with:  = void;
    foreach(int i, ref foo; foos) {
        foo = Foo(i);
    }
    foreach(ref foo; foos) {
        foo.fib.call();
    }
}

This will print out:
Hello from: 9
Hello from: 9
Hello from: 9
...

`move` semantics often require updating ptrs, so just moving structs via memcpy
will often hide atrocious bugs.

Another example where `move` is problematic is an intrusive list head:

struct Chain {
  struct Chain *prev, *next;
  ..
}

An important invariant you would want to preserve is that chain.next.prev =
&chain;

Once D freely moves Chains (or any struct that indirectly contains Chain)
around, terrible bugs will ensue.

Having move by default is OK, but is there any reason to allow move for structs
that specifically disable this(this)? I'd say this violates expectations. At
the very least a way to disable unwanted moves should exist.

--


More information about the Digitalmars-d-bugs mailing list