nested functions and closures

Steven Schveighoffer schveiguy at yahoo.com
Tue Feb 12 06:04:04 PST 2013


On Tue, 12 Feb 2013 03:23:13 -0500, Johannes Pfau <nospam at example.com>  
wrote:

> Am Mon, 11 Feb 2013 17:03:22 -0500
> schrieb "Steven Schveighoffer" <schveiguy at yahoo.com>:
>
>>
>> A nested class has an outer pointer to it's owner class.  You cannot
>> instantiate a nested class without it's owner class.
>>
>> A nested struct does NOT have a pointer to it's owner class.  It's
>> simply typed inside the class' namespace.
>>
>> FYI, nested classes were enshrined with a pointer to an outer
>> instance for two reasons:
>>
>> 1. Their footprint is larger, not as big a hit to add another pointer.
>> 2. To allow porting of Java code.
>>
>> Structs are POD for the most part, and are much more "bare metal"
>> than classes.
>>
>> Nested structs could be given an instance pointer to the owner, but
>> I think we would need a new construct for that.
>
> Thanks, I thought it was something like that. The weird part is that if
> you return a nested struct which is nested in a _function_ the compiler
> generates a closure for the function and then struct is given an
> instance pointer to the closure. But if you return a struct nested in a
> class the struct doesn't get an instance pointer.

If structs inside functions acted just like structs outside of functions,  
there would be very little reason to have them.  Functions sort of have  
their own namespace, but I don't know if that justifies having  
function-nested structs.  There are static function-nested structs, but I  
think the concept of using them with frequency is pretty new (voldemort  
types).

I actually wouldn't mind an opt-in approach to including an outer  
reference, at least for structs nested in classes (it's too dangerous to  
do this for owner structs).  I think it's too late to make that the  
default.

>
>> For your problem at hand, you may want to consider using interfaces
>> instead.  Or you can possibly embed the owner pointer manually.
>>
>> -Steve
>
> Fortunately there's no problem at hand, I was just curious :-) I
> actually use nested classes/structs and closures quite rarely.

I use nested structs for namespace in dcollections quite frequently.  For  
instance TreeMap.cursor is a nested struct.

-Steve


More information about the Digitalmars-d mailing list