C++ reference type

Tom S h3r3tic at remove.mat.uni.torun.pl
Sat Jun 24 10:01:36 PDT 2006


David Medlock wrote:
> Tom S wrote:
>> David Medlock wrote:
>>
>>> The attribute functions in classes serve this purpose do they not?
>>>
>>> C++:
>>> int& my_attr();
>>>
>>> D:
>>> void my_attr( int );
>>>
>>> use, in both cases:
>>> foo.my_attr = 100;
>>
>>
>> Unless you want to be able to say 'foo.my_attr++;'
>> or 'foo.someStruct.bar = 1;'
>>
>> The latter can be accomplished by making the function return a pointer 
>> to the struct, but then you cant say 'Foo x = my_attr();'
>>
>>
> Ok, but what exactly does that buy you?
> 
> If you want reference semantics use a class.
> If you want opPostInc use a struct.
> 
> Even without you could just as easily say:
> 
> int bar(int r) { return this.someStruct.bar = r; }
> 
> if you have several 'bars' perhaps its time to refactor?
> 
> Its like saying : I cant ride my car on bike trails, even though I can 
> ride my bike on roads.  Just use the bike.

Excuse me, but I have no idea what you're talking about. Reference 
return types are useful in many cases. E.g. if you want to implement 
your own Array class. With normal arrays you can say:

int[] arr1; ... ; arr1[0] += 2;

but when you define your own array, like:

Array!(int) arr2; ... ;

then how do you implement 'arr2[0] += 2;' ?

You can't, because there are only opIndex and opIndexAssign operators. 
There's no opIndexAddAssign and opIndex*Assign for that purpose :0

This gets worse, e.g. if you have a

struct Foo {
     int bar;
}

Foo[] arr3; ... ; arr3[0].bar = 1;

but when you define

Array!(Foo) arr4; ... ;

then to accomplish the 'arr4[0].bar = 1;' functionality, you have to 
make opIndex return a pointer. Yet then you can't say 'Foo x = arr4[0];' 
because there's a type mismatch. You'd have to dereference the pointer.


-- 
Tomasz Stachowiak  /+ a.k.a. h3r3tic +/



More information about the Digitalmars-d mailing list