swap

Swaps lhs and rhs. The instances lhs and rhs are moved in memory, without ever calling opAssign, nor any other function. T need not be assignable at all to be swapped.

If lhs and rhs reference the same instance, then nothing is done.

lhs and rhs must be mutable. If T is a struct or union, then its fields must also all be (recursively) mutable.

  1. void swap(T lhs, T rhs)
    @trusted pure nothrow @nogc
    void
    swap
    (
    T
    )
    (
    ref T lhs
    ,
    ref T rhs
    )
    if (
    isBlitAssignable!T &&
    !is(typeof(lhs.proxySwap(rhs)))
    )
  2. void swap(T lhs, T rhs)

Parameters

lhs T

Data to be swapped with rhs.

rhs T

Data to be swapped with lhs.

Examples

1 // Swapping POD (plain old data) types:
2 int a = 42, b = 34;
3 swap(a, b);
4 assert(a == 34 && b == 42);
5 
6 // Swapping structs with indirection:
7 static struct S { int x; char c; int[] y; }
8 S s1 = { 0, 'z', [ 1, 2 ] };
9 S s2 = { 42, 'a', [ 4, 6 ] };
10 swap(s1, s2);
11 assert(s1.x == 42);
12 assert(s1.c == 'a');
13 assert(s1.y == [ 4, 6 ]);
14 
15 assert(s2.x == 0);
16 assert(s2.c == 'z');
17 assert(s2.y == [ 1, 2 ]);
18 
19 // Immutables cannot be swapped:
20 immutable int imm1 = 1, imm2 = 2;
21 static assert(!__traits(compiles, swap(imm1, imm2)));
22 
23 int c = imm1 + 0;
24 int d = imm2 + 0;
25 swap(c, d);
26 assert(c == 2);
27 assert(d == 1);
1 // Non-copyable types can still be swapped.
2 static struct NoCopy
3 {
4     this(this) { assert(0); }
5     int n;
6     string s;
7 }
8 NoCopy nc1, nc2;
9 nc1.n = 127; nc1.s = "abc";
10 nc2.n = 513; nc2.s = "uvwxyz";
11 
12 swap(nc1, nc2);
13 assert(nc1.n == 513 && nc1.s == "uvwxyz");
14 assert(nc2.n == 127 && nc2.s == "abc");
15 
16 swap(nc1, nc1);
17 swap(nc2, nc2);
18 assert(nc1.n == 513 && nc1.s == "uvwxyz");
19 assert(nc2.n == 127 && nc2.s == "abc");
20 
21 // Types containing non-copyable fields can also be swapped.
22 static struct NoCopyHolder
23 {
24     NoCopy noCopy;
25 }
26 NoCopyHolder h1, h2;
27 h1.noCopy.n = 31; h1.noCopy.s = "abc";
28 h2.noCopy.n = 65; h2.noCopy.s = null;
29 
30 swap(h1, h2);
31 assert(h1.noCopy.n == 65 && h1.noCopy.s == null);
32 assert(h2.noCopy.n == 31 && h2.noCopy.s == "abc");
33 
34 swap(h1, h1);
35 swap(h2, h2);
36 assert(h1.noCopy.n == 65 && h1.noCopy.s == null);
37 assert(h2.noCopy.n == 31 && h2.noCopy.s == "abc");
38 
39 // Const types cannot be swapped.
40 const NoCopy const1, const2;
41 assert(const1.n == 0 && const2.n == 0);
42 static assert(!__traits(compiles, swap(const1, const2)));

Meta

Suggestion Box / Bug Report