== Auszug aus bearophile ([email protected])'s Artikel
> malio:
> > I'm a bit confused what exactly ref means and in which cases I definitely 
> > need this keyword.
> ref is not too much hard to understand. This is a simple usage example:
> import std.stdio;
> void inc(ref int x) {
>     x++;
> }
> void main() {
>     int x = 10;
>     writeln(x);
>     inc(x);
>     writeln(x);
> }
> It is almost syntax sugar for:
> import std.stdio;
> void inc(int* x) {
>     (*x)++;
> }
> void main() {
>     int x = 10;
>     writeln(x);
>     inc(&x);
>     writeln(x);
> }
> But a pointer can be null too.
> Beside allowing that mutation of variables, in D you are allowed to use 
> "const ref" too (or immutable ref), this is useful if your value is many 
> bytes long,
to avoid a costly copy:
> import std.stdio;
> struct Foo { int[100] a; }
> void showFirst(const ref Foo f) {
>     writeln(f.a[0]);
> }
> void main() {
>     Foo f;
>     f.a[] = 5;
>     showFirst(f);
> }
> Another use for ref is on the return argument:
> import std.stdio;
> struct Foo {
>     double[3] a;
>     ref double opIndex(size_t i) {
>         return a[i];
>     }
> }
> void main() {
>     Foo f;
>     f.a[] = 5;
>     writeln(f.a);
>     f[1] = 10;
>     writeln(f.a);
> }
> Bye,
> bearophile

Okay, thanks bearophile. But I currently doesn't exactly understand what's the 
difference between "ref" and "const ref"/"immutable ref". If "ref" is syntactic
sugar for pointers only (like your first example), does it also create a copy 
of the parameters which are marked as "ref"? I thought that pointers (and in
this context also "ref") avoid the creation of costly copies?!?

Thanks!

Reply via email to