Deprecating this(this)

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Apr 3 21:17:23 UTC 2018


On 04/03/2018 04:26 PM, ag0aep6g wrote:
> On 04/03/2018 05:13 PM, Steven Schveighoffer wrote:
>> Unfortunately, I found out that it's not just "pre-filled with some 
>> values". Member postblits are run before the containing postblit.
>>
>> https://run.dlang.io/is/mt6eGa
>>
>> So this means, the data that is available to the postblit has already 
>> been processed.
> 
> There's a similar situation with constructors: A constructor can call 
> another constructor, which can lead to double initialization of fields.
> 
> Example:
> 
> ----
> class C
> {
>      int x;
>      this() immutable
>      {
>          this(42); /* Initializes x. */
>          x = 13; /* Breaking immutable, or ok? */
>      }
>      this(int x) immutable
>      {
>          this.x = x;
>      }
> }
> ----

Let's replace "int" with an UDT:

struct S
{
     int x = -1;
     this(int y) immutable { x = y; }
     void opAssign(int) immutable;
}

class C
{
     S x;
     this() immutable
     {
         this(42); /* Initializes x. */
         x = 13; /* Breaking immutable, or ok? */
     }
     this(int x) immutable
     {
         this.x = x;
     }
}

This code compiles, and calls the constructor twice for the same object. 
Clearly that shouldn't be allowed to pass. I've submitted 
https://issues.dlang.org/show_bug.cgi?id=18719 - thanks! (The problem 
seems to occur even without immutable, it's endemic to forwarding 
constructors.)

Andre


More information about the Digitalmars-d mailing list