View source code
Display the source code in std/algorithm/mutation.d from which this
page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a
Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.
Requires a signed-in GitHub account. This works well for small changes.
If you'd like to make larger changes you may want to consider using
local clone.
Function std.algorithm.mutation.move
Moves source
into target
, via a destructive copy when necessary.
void move(T)
(
ref T source,
ref T target
);
T move(T)
(
scope ref return T source
);
If T
is a struct with a destructor or postblit defined, source is reset
to its
value after it is moved into target, otherwise it is
left unchanged.
Preconditions
If source has internal pointers that point to itself and doesn't define opPostMove, it cannot be moved, and will trigger an assertion failure.
Parameters
Name | Description |
---|---|
source | Data to copy. |
target | Where to copy into. The destructor, if any, is invoked before the copy is performed. |
Example
For non-struct types, move
just performs target = source
:
Object obj1 = new Object;
Object obj2 = obj1;
Object obj3;
move(obj2, obj3);
assert(obj3 is obj1);
// obj2 unchanged
assert(obj2 is obj1);
Example
// Structs without destructors are simply copied
struct S1
{
int a = 1;
int b = 2;
}
S1 s11 = { 10, 11 };
S1 s12;
move(s11, s12);
writeln(s12); // S1(10, 11)
writeln(s11); // s12
// But structs with destructors or postblits are reset to their .init value
// after copying to the target.
struct S2
{
int a = 1;
int b = 2;
~this() pure nothrow @safe @nogc { }
}
S2 s21 = { 3, 4 };
S2 s22;
move(s21, s22);
writeln(s21); // S2(1, 2)
writeln(s22); // S2(3, 4)
Example
Non-copyable structs can still be moved:
struct S
{
int a = 1;
@disable this(this);
~this() pure nothrow @safe @nogc {}
}
S s1;
s1 .a = 2;
S s2 = move(s1);
writeln(s1 .a); // 1
writeln(s2 .a); // 2
Example
opPostMove
will be called if defined:
struct S
{
int a;
void opPostMove(const ref S old)
{
writeln(a); // old.a
a++;
}
}
S s1;
s1 .a = 41;
S s2 = move(s1);
writeln(s2 .a); // 42
Authors
License
Copyright © 1999-2022 by the D Language Foundation | Page generated by ddox.