delegating constructors and "this = ..."

jpf spam at example.com
Mon Feb 8 11:19:49 PST 2010


On 08.02.2010 18:26, BCS wrote:
> Hello JPF,
> 
>> Hi,
>> I've come across some strange behavior using delegating constructors
>> and
>> assignment to this. Please have a look a this testcase:
>> --------------------------------------
>> class Test
>> {
>> static Test[void*] lookupTable;
>> public int i = 0;
>> public this (void* ptr)
>> {
>> //Check if there already is a D object for this ptr
>> if(ptr in lookupTable)
>> {
>> this = lookupTable[ptr];
>> assert(this.i == 15);    /* ok */
>> return;
>> }
> 
> 'this' is a mutable *local* reference (IIRC it is in fact a hidden 1st
> argument to the function). All the 'this =' lines does is assign to a
> local value that is discarded immediately. If asserts are turned off,
> the optimizer would even be free to just dump the then clause from that
> code as a dead assignment.
> 
> ('this' being mutable might be considered a bug in the spec)
> 
>>
> -- 
> <IXOYE><
> 
> 
Thanks for your help, I think I now understand what's going on.
'this' is a mutable local reference in the constructor but the
constructor automatically returns the local 'this'. This explains why
the first case works while the second doesn't. This would also mean I
could do "this = this(ptr);" in the second constructor and it indeed
does work; With the above change the whole testcase works as expected. I
now just have to decide whether I'll use the "implementation specific
but nice syntax" way or a static function instead of public constructors.



More information about the Digitalmars-d mailing list