What does ref means

malio youdontwantknow at unknown.com
Tue Sep 6 06:03:31 PDT 2011


== Auszug aus Steven Schveighoffer (schveiguy at yahoo.com)'s Artikel
> On Tue, 06 Sep 2011 05:28:22 -0400, malio <youdontwanttoknow at unknown.com>
> wrote:
> > Hi guys,
> >
> > I'm a bit confused what exactly ref means and in which cases I
> > definitely need this keyword.
> ref is simple.  It's a pointer, but without the messy pointer syntax.
> These two programs are exactly the same (will generate the same code):
> void foo(int *i)
> {
>     *i = 5;
> }
> void main()
> {
>     int x = 2;
>     foo(&x);
> }
> ----------------------
> void foo(ref int i)
> {
>     i = 5;
> }
> void main()
> {
>     int x = 2;
>     foo(x); // note, there's no need to use &, the compiler does it for you
> }
> -Steve

> malio:
> > 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?!?
> "ref" just passes a reference to something, so it doesn't perform copies.
> "const ref" or "immutable ref" just means that you can't change the value
(with the usual semantic differences between const and immutable, that are both
transitive).
> For the programmer that reads your code, "ref" means the function you have
written will usually modify the given argument, while "const ref" means it will
not modify it.
> Bye,
> bearophile

Ah, okay - thanks in advance bearophile and Steve :)


More information about the Digitalmars-d-learn mailing list