important proposal: scope keyword for class members

Sean Kelly sean at invisibleduck.org
Sun Mar 8 10:15:10 PDT 2009


Christopher Wright wrote:
> Sean Kelly wrote:
>> Andrei Alexandrescu wrote:
>>> Sean Kelly wrote:
>>>> John Simon wrote:
>>>>> I'd like to propose a new use for the 'scope' keyword within an 
>>>>> aggregate body.
>>>>>
>>>>> Members of class type declared with the scope keyword are allocated 
>>>>> not as references or pointers, but initialized directly inside the 
>>>>> container.  Instead of a default initializer of 'null', it will 
>>>>> initialize with the default constructor of the class, or an 
>>>>> optional assignment after the declaration. Any 'new [type]' within 
>>>>> the assignment will resolve to a simple call to the type's __ctor, 
>>>>> instead of a memory allocation.
>>>>
>>>> A while back, Walter said that he planned to do exactly this.  I'm 
>>>> not sure what the timetable is though, or if plans have changed.
>>>
>>> I'd be happier if we investigated scope in classes as an ownership 
>>> mechanism. In-situ storage is nice, but ownership management is more 
>>> important.
>>
>> Yeah, in-situ storage would just be a QOI feature like it is for scope 
>> variables at function level.  I agree that the logical effect of scope 
>> at class level is more important.
> 
> You're talking about something like this?
> class A
> {
>     scope Object o;
>     this ()
>     {
>         o = new Object;
>     }
> }
> 
> converts to:
> class A
> {
>     Object o;
>     this ()
>     {
>         void* ptr = gc.allocAndIgnore(Object.classinfo.size);
>         o = new(ptr) Object;
>     }
>     ~this ()
>     {
>         delete o;
>     }
> }

For the logical aspect of scope variables, I was thinking more about 
possibly restricting whether they are allowed to escape from the scope 
in which they are declared, etc.  The QOI feature would be to make the 
related allocations occur within the enclosing scope.  So, for example:

class C { byte[16] x; }

Object fn()
{
     scope C var = new C; // allocated on the stack
     return var; // possibly flagged as an error by the compiler
}

class D
{
     scope C var;
     this()
     {
         var = new C; // in-place constructed within D
     }

     C get()
     {
         return var; // possibly flagged as an error
     }
}



More information about the Digitalmars-d mailing list