An important potential change to the language: transitory ref

Don nospam at nospam.com
Sat Mar 20 00:36:50 PDT 2010


Andrei Alexandrescu wrote:
> On 03/20/2010 12:56 AM, Steven Schveighoffer wrote:
>> On Sat, 20 Mar 2010 00:07:55 -0400, Andrei Alexandrescu
>> <SeeWebsiteForEmail at erdani.org> wrote:
>>> I remember you brought up a similar point in a related discussion a
>>> couple of years ago. It's a good point, and my current understanding
>>> of the matter is that functions that take and return ref could and
>>> should be handled conservatively.
>>
>> I don't like the sound of that... What I fear is that the compiler will
>> force people to start using pointers because refs don't cut it. I'm
>> guessing you mean you cannot return ref returns from other functions?
>> That breaks abstraction principles, I should be able to delegate a task
>> to a sub-function.
> 
> Perhaps it means you can't return ref returns from other functions if 
> you pass them references to local state.
> 
> (I've read a paper at some point about a program analysis that stored 
> for each function the "return pattern" - a mini-graph describing the 
> relationship between parameters and result. If it rings a bell to 
> anyone... please chime in.)
> 
>>>> For instance, try to find a rule that prevents the above from 
>>>> compiling,
>>>> but allows the following to compile.
>>>>
>>>> struct S
>>>> {
>>>> private int x;
>>>> ref int getX() { return x;}
>>>> }
>>>>
>>>> struct T
>>>> {
>>>> S s;
>>>> ref int getSX() { return s.x; }
>>>> }
>>>
>>> In the approach discussed with Walter, S is illegal. A struct can't
>>> define a method to return a reference to a direct member. This is
>>> exactly the advice given in Scott's book for C++. (A class can because
>>> classes sit on the heap.)
>>
>> A struct may sit on the heap too.
> 
> Yes. For those cases you can always use pointers, which are not subject 
> to the restrictions I envision for ref.
> 
> It's a very small inconvenience. For example, if you have a linked list 
> struct, you may feel constrained that you can't do:
> 
> struct List {
>     List * next;
>     List * prepend(List * lst) {
>         lst.next = &this;
>         return lst;
>     }
> }
> 
> In my approach, &this is illegal. And actually for a good reason. This 
> code bombs:
> 
> List iForgotThePointer() {
>     List lst;
>     lst.prepend(new List);
>     return lst;
> }
> 
> My response to the above issue is two-pronged:
> 
> (a) For List a class would be an alternative
> (b) To work with pointers to structs use static member functions and 
> pointers instead of methods and references

That would prohibit their use in safe D, right?

Although I can see the appeal of this idea, it seems very experimental. 
I fear it might have unexpected consequences. So it would need quite 
extensive testing. Do we have enough time to do that?



More information about the Digitalmars-d mailing list