What does ref means

bearophile bearophileHUGS at lycos.com
Tue Sep 6 03:08:22 PDT 2011


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


More information about the Digitalmars-d-learn mailing list