Move Constructors - Converting Lvalues to Rvalues
Vindex9
tech.vindex at gmail.com
Tue Oct 1 12:58:47 UTC 2024
On Monday, 30 September 2024 at 16:05:16 UTC, Walter Bright wrote:
> I've been implementing move constructors. They are working, at
> least on my test cases so far. They are distinguished by a copy
> constructor takes its argument by ref, and a move constructor
> by value:
>
> ```
> struct S
> {
> this(ref S); // copy constructor
> this(S); // move constructor
> }
---
Is it necessary to breed entities? Doesn't std.algorithm.move do
everything we need?
```d
import core.stdc.stdlib : malloc, free;
import core.stdc.string : memcpy;
import std.algorithm.mutation : move;
import std.exception : enforce;
import std.stdio : writeln;
struct S {
void* content;
size_t size;
this(size_t n) {
writeln("regular ctor"); // debug
init(n);
}
this(ref return scope const S rhs) {
writeln("copy ctor"); // debug
init(rhs.size);
memcpy(this.content, rhs.content, rhs.size);
}
private void init(size_t n) {
this.content = malloc(n);
enforce(this.content != null, "Memory allocation error.");
this.size = n;
}
}
void main() {
S obj1 = S(1024);
assert(obj1.content != null);
S obj2 = move(obj1); // moving
assert(obj1.content == null);
assert(obj2.content != null);
S obj3 = S(obj2); // copying
assert(obj3.content != obj2.content);
assert(obj3.size == obj2.size);
}
```
More information about the Digitalmars-d
mailing list