Will D ever get a reference type?
Bill Baxter
dnewsgroup at billbaxter.com
Sun Jul 29 21:13:43 PDT 2007
BCS wrote:
> Reply to Bill,
>
>> BCS wrote:
>>
>>> Reply to Bill,
>>>
>>>> Will D ever get a reference type?
>>>>
>>>> I don't think pointers are really sufficient.
>>>> The handy 'foo.bar' == '(*foo).bar' attribute access is nice, but it
>>>> doesn't allow you to really manipulate values and pointers to values
>>>> interchangeably.
>>>> For instance, if I have an int pointer, x, I can't do (12 + x * 2)
>>>> and
>>>> get integer math. I get pointer math (if not an error).
>>>> --bb
>>> is the ref argument type more along the lines you are looking for?
>>>
>>> void Foo(ref int a)
>>>
>>> I know this is limited to arguments but other than that...
>>>
>> Yep, exactly like in the argument,
>
> <Nods>
>
>> but something that's return-able as
>> well.
>>
>
> that's worth thinking about the effects of
>
>> --bb
One interaction is that all the D substitutes for returnable reference
types become somewhat redundant. Like for property syntax:
class Foo
{
ref int prop() { return _prop; }
ref int prop(int x) { return _prop = x; }
private:
int _prop;
}
foo.prop = 10 could now be implemented by the compiler either as getter
followed by assigning to the ref, or by calling the setter.
I haven't really been able to think of a case where a reference type
per-se is absolutely essential, which is one reason why I asked the
question. But I think what *is* absolutely essential is a way to return
some sort of proxy that acts just like a Foo but in fact is really only
a go-between for a Foo. References are in one sense just really dumb
proxies that can't do anything but blindly forward requests unmodified
directly to the object being proxied. They give anyone direct,
unprotected access to the underlying object's state, which is usually
not desirable in terms of encapsulation. So in C++ some folks say you
should never return a reference to a member. If you're doing that you
might as well have people access the member directly because once you
return the reference you have no control over what the caller does to
it, and have no way of knowing if or when they modify it.
I posit that what you really want most of the time is to return
something to the caller that acts just like a Foo, but still gives you
some control, perhaps in the form of preventing certain operations,
and/or giving you a way to observe modifications. References and const
references are like simple proxies with the rules "you can do anything"
and "you can do anything involving read-only operations".
Well, that's about all the time I have for thinking about it right now.
But I'm starting to think that reference types aren't necessary as
long as you have an semi-efficient way to wrap *any* type with an object
that can act just like it. I think somebody has been talking about
trying to implement such a thing recently, but I can't recall who.
--bb
More information about the Digitalmars-d
mailing list