Sean Kelly 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.
>
> Oh, I should mention that I'm not sure how the compiler would handle
> this scenario:
>
> class A { byte[16]; }
> class B { byte[32]; }
> class C {
> this( bool b ) {
> if( b ) o = new A;
> else o = new B;
> }
> scope Object o;
> }
>
> If I had to guess I'd say that the compiler would either reserve the max
> size necessary to store both A or B, or that in non-trivial cases it
> just wouldn't bother with reserving space for o at all.
Wrong. The Object is constructed when it comes into scope, and destructed when
it leaves scope. Classes can't have an 'opAssign', instead the reference is
reassigned. Since the reference is invariant/immutable here, this throws a
compile time error.
In C++ it's equivalent to:
class Object{void *classInfo; ...};
class A : Object {};
void normalDClass() {
Object *o;
o = new A(); // OK!
o = new B(); // OK!
}
void scopeDClass() {
Object o; // initialized when entering function
o = A();
// usually calls operator=(A &), i.e. opAssign(A &).
// This is forbidden in D since A& is implicitly converible to Object.
// Therefore a compile time error happens.
// also, o is destructed here
}
The existing rules would work very well. The only thing you need to be careful
of, is not to pass the object to someone who will keep the reference around.