[Issue 16131] A struct is being copied unnecessarily when initialized
via Digitalmars-d-bugs
digitalmars-d-bugs at puremagic.com
Wed Jun 8 01:26:20 PDT 2016
https://issues.dlang.org/show_bug.cgi?id=16131
Ketmar Dark <ketmar at ketmar.no-ip.org> changed:
What |Removed |Added
----------------------------------------------------------------------------
Status|REOPENED |RESOLVED
Resolution|--- |INVALID
--- Comment #4 from Ketmar Dark <ketmar at ketmar.no-ip.org> ---
sorry, but i have to close this bug again. it is perfectly valid to move
*value* type. struct is *value* type. you can't disable "move" operations on
structs, and this is not an oversight, it was designed like that. it gives
compiler some freedom, and it won't be changed.
never ever store a pointer to stack-allocated struct anywhere. this is The
Rule.
as for lists... allocate your structs with `new` — and compiler will not move
'em. then you can do what you want.
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 = new Foo(i);
}
foreach(ref foo; foos) {
foo.fib.call();
}
}
This will print out:
Hello from: 0
Hello from: 1
Hello from: 2
Hello from: 3
Hello from: 4
Hello from: 5
Hello from: 6
Hello from: 7
Hello from: 8
Hello from: 9
as you can see, heap-allocated structs won't be moved, never (unless somebody
will write compating GC ;-).
so, to summarise: there is no sense to complain about "move" semantic for
structs, it works as designed, and will stay with us. just have it in mind when
you designing your code. sorry.
--
More information about the Digitalmars-d-bugs
mailing list