Owned members

Alex Khmara alex.khmara at gmail.com
Sat Dec 25 13:23:47 PST 2010


On Sat, 25 Dec 2010 14:42:48 -0000, bearophile <bearophileHUGS at lycos.com>  
wrote:

> spir:
>
>> I would enjoy to see a concrete, meaningful, example.
>
> Often enough my class/struct members are arrays, and often I'd like the  
> compiler to help me be more sure their memory is not shared (with a  
> slice, for example) with something outside the instance. See below.
>
>
>> It seems your point is to avoid sharing ref'ed elements --which is  
>> precisely the purpose of referencing, isn't it?
>
> That's one of the purposes of references, but there are other purposes.  
> A dynamic array is allocated on the heap through a kind of fat reference  
> so you are able to change its length. Objects in D are always managed by  
> reference, so you have no choice.
>
>
>> What is the sense of having referenced elements if the references are  
>> not to be shared?
>
> They are owned by the class instance :-) And even if you use emplace or  
> scoped from Phobos, you still have a reference, so @owned is useful even  
> for scoped objects.
>
>
>> Then, you would need a tag like @owned to give back value semantics to  
>> referenced elements... Correct?
>
> @owned doesn't change the semantics and probably the resulting binary is  
> unchanged. Its purpose is just to disable certain undesired (and buggy)  
> behaviours, to keep class instance the only owner of the referenced  
> object/array.
>
>
>> What about the opposite (much rarer) case:
>
> It's another thing.
>
>
>> Googling should point you to 2-3 articles by Bertrand Meyer
>
> I remember something by Meyer, but I don't remember if he was talking  
> about instance ownership. I will read something again.
>
> Bye,
> bearophile

I don' understand how this can be implemented in more complicated cases:

class X {
      @owned private int[] foo;
      int[] f1() {
         auto fooSlice = foo[0...3];                 // is this valid?
         someExternalFunc(foo);                      // is this allowed?
         someExternalFunc(fooSlice)                  // how about this?
         return someFuncReturningArrayArg(fooSlice); // how to detect this?
     }
}

It seems that @owned can work only in very primitive cases - otherwise  
complex escape
analysis needed, and I even do not know if it will help. May be, if only  
pure function will be
allowed to accept @owned arguments, it will be ok, but power of this  
feature will be
severely limited in this case.


More information about the Digitalmars-d mailing list