re-creating C++'s reference bahavior
akcom
CppCoder at gmail.com
Mon Apr 16 21:48:51 PDT 2007
> 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.
What about situations in which you're not just returning a reference to a
class object? A templated hash map implementation for example, may want to
do something like the D equivalent of
template <class T, class K >T &HashMap<T,K>::find( K )
Things become a bit trickier if you're dealing with basic types.
"Daniel Keep" <daniel.keep.lists at gmail.com> wrote in message
news:f0160f$bau$1 at digitalmars.com...
>
>
> 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)?
>
>
> 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