re-creating C++'s reference bahavior

Daniel Keep daniel.keep.lists at gmail.com
Mon Apr 16 17:56:29 PDT 2007



swiftcoder - Tristam MacDonald wrote:
> I am fairly new to D, from a C++ background, and I am having a hard time coming up with a sensible way to deal with what is a fairly trivial example in C++:
> 
> class Vector3f;
> 
> class Node
> {
> Vector3f &position();
> };
> 
> Node n;
> 
> n.position().x = 0; // Works as expected, sets n.position().x to 0
> 
> Vector3f v = n.position();
> v.x = 10; // Works as expected in C++ since v is a copy of n.position()
> 
> But now in D, I find that the last statement requires an explicit copy on the user's part, otherwise they are using the actual instance, and may do nasty things to it unintentionally. The obvious fix is to copy the vector in Node.position(), but then you have lost the benefits of references, namely to modify the variable. So it would seem that the only way to handle this is to return a copy in the getter function, and  require explicit setting with the setter method (thus losing constructs such as n.position().x = 0)?

AFAIK, there's really no way to exactly duplicate C++'s references.
However, if all "position()" is doing is returning a reference to a
vector, then do you really need a function at all?  If you just use a
member variable, then the problem disappears.

And incidentally, you can omit the parens with D since it's a function
with no arguments. ie:

> auto v = n.position;
> v.x = 10;

("auto" is used here to trigger type inference -- if you specify a
variable's storage class, you can omit the type itself.)

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/


More information about the Digitalmars-d-learn mailing list