Temporaries / struct RAII patterns

Witold witold.baryluk+dlang at gmail.com
Mon Oct 16 18:15:46 UTC 2023


So it looks like to ensure RVO (return value optimization), I 
need to write it like this:

```d
X Foo(string fmt, Args...)(lazy Args args, string file = 
__FILE__, int line = __LINE__) {
   auto r = X(message, file, line);
   r.F!(fmt, Args)(args);
   return r;
}
```

Instead of:

```d
X Foo(string fmt, Args...)(lazy Args args, string file = 
__FILE__, int line = __LINE__) {
   return X(message, file, line).F!(fmt, Args)(args);
}
```


Otherwise copy constructor is called. In this case I can emulate 
"move" semantic using copy constructor:

```d
struct X {
   @disable this();
   this(ref X other) {
     message = other.message;
     file = other.file;
     line = other.line;
     kvs = other.kvs;

     // mark other moved out
     other.message = null;
     other.file = null;
     other.line = -1;
     other.kvs = null;
   }

   // ...
   ~this() {
     // Only do action if it was not moved out by "copy" 
constructor
     if (message !is null) {
       DoSomething(&this, message, kvs);
     }
   }
}
```


But it is so so.

I do not plan to expose `X` type directly, so nobody but the 
library should be creating it, but user can technically assign it 
to variables (there are reasons for this), for future 
manipulation.



More information about the Digitalmars-d mailing list