inner member classes in final outer class

Kirk McDonald kirklin.mcdonald at gmail.com
Sat Sep 15 15:31:55 PDT 2007


coxalan wrote:
> Frits van Bommel Wrote:
> 
> 
>> I just looked it up; from the documentation (the page you linked
>> above): ===== Non-static nested classes work by containing an extra
>> hidden member (called the context pointer) that is the frame
>> pointer of the enclosing function if it is nested inside a
>> function, or the this of the enclosing class's instance if it is
>> nested inside a class. =====
>> 
>> In the code above the class is nested in another class (not a
>> function), so the context pointer is the 'this' of the enclosing
>> class, i.e. a copy of 'o'.
> 
> 
> Yes, the "this" of the outer class is stored in each inner member
> class. So on a 32 bit machine: Each inner class contains 4 extra
> bytes storing the address of the outer class (This is what I meant by
> using the term "pointer": An address is stored.)
> 
> In my code example, the outer class 'o' is final. That means that the
> reference stored in 'o' will never change, so for all instances of
> 'o.Inner' the address stored in the context pointer will be the same.
> This is redundant, and I wonder if the optimization could be done to
> _not_ store the reference pointers for instances of member classes of
> final outer classes.

That o is final is irrelevant. Consider:

Outer.Inner foo() {
     final Outer o = new Outer;
     return o.new Inner;
}

The lifetime of the instance of the Inner class can easily exceed that 
of the original reference to the instance of the Outer class which 
created it. Therefore, the Inner class must have its own reference to 
the Outer class.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org



More information about the Digitalmars-d mailing list