re-creating C++'s reference bahavior

swiftcoder - Tristam MacDonald swiftcoder at darkcoda.com
Mon Apr 16 17:47:31 PDT 2007


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)?


More information about the Digitalmars-d-learn mailing list