References

Ali Çehreli acehreli at yahoo.com
Sun Nov 27 23:07:45 PST 2011


On 11/28/2011 05:41 PM, David Currie wrote:
 > I am a newbie to D. From (C++,Java,others...) background.
 >
 > In C++ I can say
 >
 > void f1(int& pInt)
 > {
 > pInt = 1;
 > }
 >
 > which sets pInt(which is outside f1)
 > because although pInt (at compile time) is a Value
 > in reality it is passed by reference(address).
 >
 > Now
 >
 > void f2(int* pIntPtr)
 > {
 > *pIntPtr = 1;
 > ++pIntPtr;
 > *pInt = 2;
 > }
 > sets (the contents of) pInt to 1 (and the next immediate address to 2)
 >
 > All this is of course standard C++.
 >
 > How is this type of thing done in D
 > (changing objects by passing by reference etc)?

Pointers are the same in D but needed far less than C++.

For parameter passing, the ref keyword can be used:

void f3(ref int pInt)
{
     // ...
}

Also check out 'out' parameters:

void f4(out int pInt)
{
     // ...
}

The difference from ref is the fact that out parameters are initialized 
to .init of their type when entering the function. They are documented 
here: http://d-programming-language.org/function.html

Additionally, you may find it surprising that classes are reference 
types in D (unlike structs, which are value types as in C and C++). So 
you don't need to use the ref keyword, as the class object would be 
passed by reference as the class variable:

class C
{
     // ...
}

void f5(C c)  // <-- reference to the class object
{
     // ...
}

Other reference types of D are dynamic arrays and associative arrays 
(importantly, fixed-length arrays are value types!)

Ali



More information about the Digitalmars-d-learn mailing list