C++ reference type

Dave Dave_member at pathlink.com
Sat Jun 24 10:55:22 PDT 2006


Hasan Aljudy wrote:
> Yossarian wrote:
>> Tesuji napsal(a):
>>
>>> Will C++ reference type ever be included in D? In one form or the other?
>>>
>>>
>> what do you mean? every complex object is internally passed by 
>> reference, and if you want the same behaviour as in c++ references, 
>> try inout keyword in declaration:
>> D:   void func(inout int a);
>> is equal to
>> C++: void func(int &a);
> 
> The only thing missing is a reference return type.

There's one more irritating limitation, and that is the ability to pass 
a temporary byref:

private import std.stdio;
void main()
{
     // error: (opCall)(100) is not an lvalue
     writefln(foo(MyStruct(100),100));
}
int foo(inout MyStruct s, int i)
{
     return s.i * i;
}
struct MyStruct
{
     private int i = 0;
     static MyStruct opCall(int i)
     {
         MyStruct s;
         s.i = i;
         return s;
     }
}

I think the 'byref' modifier could be added to allow this. In the 
compiler it could be implemented the same as 'inout' except that the 
lvalue limitation would not be enforced.

In C++ you'd have to do 'const <type> &', but I'm not suggesting we get 
into the const debate again just for this purpose; just add the byref 
for cases like that, for cases where the programmer just wants to pass 
byref w/o an intention to modify the parameter, and also the 'byref' 
modifier could then be used for function return types as well (makes 
more sense to me than using 'inout' for return types).

- Dave



More information about the Digitalmars-d mailing list