Move Constructor Syntax

Salih Dincer salihdb at hotmail.com
Sun Oct 6 18:31:41 UTC 2024


On Sunday, 6 October 2024 at 04:04:28 UTC, Walter Bright wrote:
> ```d
> struct S { ... }
>
> this(ref S) // copy constructor
> this(this)  // postblit
> this(S)     // move constructor
> ~this()     // destructor
>
> alias T = S;
> this(T);    // also move constructor
>
> alias Q = int;
> this(Q);    // regular constructor
> ```
> As the above illustrates, a move constructor cannot be 
> distinguished from a regular constructor by syntax alone. It 
> needs semantic analysis.
> ...

Option 3 is really bad, but I like option 2. In this syntax, the 
= operator is at the beginning of the parameter. This could mean 
that the parameter is inherited. In other words, we are 
transferring the source of the S object to the this object.

```d
struct MyStruct {
     int[] data;

     this(int size) {
         data = new int[size];
         writeln("Constructor called, data: ", data);
     }

     this(=MyStruct other) {
         data = other.data;
         other.data = null;
         writeln("Move constructor called");
     }
}
```
SDB at 79



More information about the Digitalmars-d mailing list