Andrei Alexandrescu:
> class B {
> scope A a;
> this() {
> a = new A;
> }
> }
>
> Now the A member actually lies inside of B - no more indirection. That
> means the constructor needs special scrutiny, in particular a cannot be
> null because that wouldn't make much sense.
> What do you think?
I have recently discussed about this. One idea is to keep the compiler simpler,
keeping such scoped class as possible similar to normal class. So you keep the
indirection. So B keeps inside itself the memory needed to keep an A plus a
reference to A itself. This wastes a little memory for the reference and keeps
the indirection, but allows to keep the semantics of A almost unchanged,
because you can always do reassign "a" to another instance of A (an instance
that can allocated on the heap too).
In such situation the main and maybe only thing you have to keep care of is the
deallocation of "a", that has to not happen (well, you can call its destructor,
but you can't actually free its memory), because even if the GC has declared it
as dead (because of a "delete" or because "a" has being reassigned to something
else), it can't be deallocated until the instance of B is deallocated.
There are other ways to implement this, but I think they require more
special-casing and more changes to the frontend and probably a little more
complexity.
Bye,
bearophile