Owned members

spir denis.spir at gmail.com
Sat Dec 25 03:03:05 PST 2010


On Sat, 25 Dec 2010 04:06:15 -0500
bearophile <bearophileHUGS at lycos.com> wrote:

> I am far from being an expert C++ (or OOP) programmer still, so probably some of my needs look (or are) naive.
> 
> This looks related to the old discussion of a 'scoped' attribute for class members, but it's a different thing, more about the semantics of the code and less about how the compiler implements things.
> 
> Sometimes I feel the need for something (usable on class/struct/enum members) to tag a member as "owned" by the class instance. This attribute is useful only for reference attributes, like objects, structs managed by pointer, associative arrays and dynamic arrays. This attribute is purely a type system thing, the compiled code doesn't change. It just disallows some kinds of code, shown below. The purpose of @owned is to hopefully avoid some bugs.
> 
> 
> class Foo {}
> 
> class Bar {
>     @owned private int[] array;
>     @owned private f Foo;
>     
>     public int[] giveArray() {
>         return array; // error, a dup is required
>     }
>     public void receiveArray(int[] a) {
>         array = a; // error, a dup is required
>     }
> 
>     public Foo giveFoo() {
>         return f; // error
>     }
>     public void receiveFoo(Foo ff) {
>         f = ff; // error
>     }
> }
> 
> 
> If array is owned by Bar, then "return array;" is a compile-time error because the memory of the array is only owned by Bar; returning a slice or reference is not allowed.
> 
> Is it possible to implement this @owned, and is it a good thing to have?


I would enjoy to see a concrete, meaningful, example.

It seems your point is to avoid sharing ref'ed elements --which is precisely the purpose of referencing, isn't it?  What is the sense of having referenced elements if the references are not to be shared?
On the other hand, refs may be useful from an implementation point of vue, but not match the semantics. Then, you would need a tag like @owned to give back value semantics to referenced elements... Correct?

What about the opposite (much rarer) case: An element that is typcally implemented as a value but conceptually is a referenced entity with identity. For instance, a plain string or even an int (here, actually a nominal) representing a font (via its name or any kind of code). ?

Googling should point you to 2-3 articles by Bertrand Meyer on the late introduction in Eiffel of a possibly related feature (don't remember how he called that). A typical case beeing the engine of a car: it is "owned" by, it belongs, to the car. But it's still a proper entity with identity (and can be shared, indeed, for instance a factory or car workshop may hold a ref to it.)

AFAIK, neither of those concepts is commonly present in OO languages.


Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list