Better handling of noncopyable objects and objects with this(this)

via Digitalmars-d digitalmars-d at puremagic.com
Mon Jun 1 07:43:20 PDT 2015


On Monday, 1 June 2015 at 14:20:46 UTC, Jonathan M Davis wrote:
> On Monday, 1 June 2015 at 12:50:28 UTC, Marc Schütz wrote:
>> Also, object with destructors need to have more restrictions:
>>
>>    S {
>>        ~this();
>>    }
>>
>>    void foo() {
>>        S s;
>>        if(condition)
>>            bar(s);
>>        // <- should we run the destructor here?
>>    }
>>
>> This can either be solved by making such cases non-eligible, 
>> or by "remembering" whether an object was moved using a hidden 
>> boolean variable. AFAIK the latter is incidentally the 
>> solution Rust chose.
>
> Wouldn't the compiler just do something like
>
> if(condition)
> {
>     bar(s); // Do a move; the destructor is run inside bar
>     return;
> }
> else
> {
>     s.__dtor();
>     return;
> }
>
> In which case, the destructor is always run in the right spot, 
> and the compiler can guarantee that a move is done rather than 
> a copy?

When this can be done, it's of course a good solution. But when 
there is additional code between the move and the destruction, it 
usually doesn't work:

     void foo() {
         S s;
         if(condition)
             bar(s);
         baz();
         // <- should we run the destructor here?
     }


More information about the Digitalmars-d mailing list