About ref used for performance reasons with struct
deadalnix
deadalnix at gmail.com
Mon Feb 11 02:53:39 PST 2013
On Monday, 11 February 2013 at 10:04:55 UTC, Namespace wrote:
> But what if we want to pass a struct with intent as value?
> With this solution, we don't have much control.
> In general, I like the idea, but we should mark such parameter
> with '&' or whatever, so at least we can still take some
> influence.
That is the whole point, everything appear as if it is passed by
value.
struct A {
uint member;
this(this) {
// Very long but pure operation.
}
}
void main() {
A a;
foo(a);
assert(a.member = 0); // Pass.
}
void foo(A a) { // Compiler can choose to pass by ref here.
bar(a);
}
void bar(A a) { // If compiler choose to pass by ref, then it is
bar responsibility to create a copy. A smarter move from the
compiler is to mark bar as non electable for such optimization.
a.member = 5;
}
In the example above, the compiler is allowed to pass a by ref to
foo. As a consequence, the very long operation within the
postblit can only be executed once, instead of 2.
More information about the Digitalmars-d
mailing list