www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - What is the purpose of -preview=dtorfields?

reply Per =?UTF-8?B?Tm9yZGzDtnc=?= <per.nordlow gmail.com> writes:
I'd appreciate if somebody elaborated a bit on the purpose of the 
compiler flag

     -preview=dtorfields       destruct fields of partially 
constructed objects
Aug 31 2020
next sibling parent reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
On Mon, Aug 31, 2020 at 08:22:02PM +0000, Per Nordlöw via Digitalmars-d wrote:
 I'd appreciate if somebody elaborated a bit on the purpose of the
 compiler flag
 
     -preview=dtorfields       destruct fields of partially constructed
 objects
My guess is to be completely exception-safe. For example: class Resource(T) { T* handle; this(...) { handle = acquireResource(...); } ~this() { releaseResource(handle); } } class ResCollection { Resource!A resA; Resource!B resB; this() { resA = new Resource!A(...); resB = new Resource!B(...); } } If an exception is thrown during the call to `new Resource!B`, the current behaviour is that resA is not destructed, so there may potentially be a resource leak. The abovementioned compiler flag is to force destruction of resA in case resB fails to be initialized (i.e., as if you wrote `scope(failure) delete(resA);` after the `resA = ...` line). T -- Кто везде - тот нигде.
Aug 31 2020
parent Per =?UTF-8?B?Tm9yZGzDtnc=?= <per.nordlow gmail.com> writes:
On Monday, 31 August 2020 at 20:34:23 UTC, H. S. Teoh wrote:
 My guess is to be completely exception-safe. For example:
Nice. Thanks.
Aug 31 2020
prev sibling parent Simen =?UTF-8?B?S2rDpnLDpXM=?= <simen.kjaras gmail.com> writes:
On Monday, 31 August 2020 at 20:22:02 UTC, Per Nordlöw wrote:
 I'd appreciate if somebody elaborated a bit on the purpose of 
 the compiler flag

     -preview=dtorfields       destruct fields of partially 
 constructed objects
With this code: struct S1 { this(int) {} ~this() { import std.stdio; writeln("~S1"); } } struct S2 { S1 s1; S1 s2; this(int i) { s1 = S1(0); throw new Exception(""); s2 = S1(0); } } void main() { S2 a = S2(2); } The current behavior is to not destruct the s1 and s2 fields, but -preview=dtorfields ensures they will be destructed. I kinda expected only s1 to be destructed above, but s2 follows it down the drain. -- Simen
Aug 31 2020