1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 /* C++11-style, but C++98-usable, "move references" implementation. */
8 
9 #ifndef mozilla_Move_h
10 #define mozilla_Move_h
11 
12 #include "mozilla/TypeTraits.h"
13 
14 namespace mozilla {
15 
16 /*
17  * "Move" References
18  *
19  * Some types can be copied much more efficiently if we know the original's
20  * value need not be preserved --- that is, if we are doing a "move", not a
21  * "copy". For example, if we have:
22  *
23  *   Vector<T> u;
24  *   Vector<T> v(u);
25  *
26  * the constructor for v must apply a copy constructor to each element of u ---
27  * taking time linear in the length of u. However, if we know we will not need u
28  * any more once v has been initialized, then we could initialize v very
29  * efficiently simply by stealing u's dynamically allocated buffer and giving it
30  * to v --- a constant-time operation, regardless of the size of u.
31  *
32  * Moves often appear in container implementations. For example, when we append
33  * to a vector, we may need to resize its buffer. This entails moving each of
34  * its extant elements from the old, smaller buffer to the new, larger buffer.
35  * But once the elements have been migrated, we're just going to throw away the
36  * old buffer; we don't care if they still have their values. So if the vector's
37  * element type can implement "move" more efficiently than "copy", the vector
38  * resizing should by all means use a "move" operation. Hash tables should also
39  * use moves when resizing their internal array as entries are added and
40  * removed.
41  *
42  * The details of the optimization, and whether it's worth applying, vary
43  * from one type to the next: copying an 'int' is as cheap as moving it, so
44  * there's no benefit in distinguishing 'int' moves from copies. And while
45  * some constructor calls for complex types are moves, many really have to
46  * be copies, and can't be optimized this way. So we need:
47  *
48  * 1) a way for a type (like Vector) to announce that it can be moved more
49  *    efficiently than it can be copied, and provide an implementation of that
50  *    move operation; and
51  *
52  * 2) a way for a particular invocation of a copy constructor to say that it's
53  *    really a move, not a copy, and that the value of the original isn't
54  *    important afterwards (although it must still be safe to destroy).
55  *
56  * If a constructor has a single argument of type 'T&&' (an 'rvalue reference
57  * to T'), that indicates that it is a 'move constructor'. That's 1). It should
58  * move, not copy, its argument into the object being constructed. It may leave
59  * the original in any safely-destructible state.
60  *
61  * If a constructor's argument is an rvalue, as in 'C(f(x))' or 'C(x + y)', as
62  * opposed to an lvalue, as in 'C(x)', then overload resolution will prefer the
63  * move constructor, if there is one. The 'mozilla::Move' function, defined in
64  * this file, is an identity function you can use in a constructor invocation to
65  * make any argument into an rvalue, like this: C(Move(x)). That's 2). (You
66  * could use any function that works, but 'Move' indicates your intention
67  * clearly.)
68  *
69  * Where we might define a copy constructor for a class C like this:
70  *
71  *   C(const C& rhs) { ... copy rhs to this ... }
72  *
73  * we would declare a move constructor like this:
74  *
75  *   C(C&& rhs) { .. move rhs to this ... }
76  *
77  * And where we might perform a copy like this:
78  *
79  *   C c2(c1);
80  *
81  * we would perform a move like this:
82  *
83  *   C c2(Move(c1));
84  *
85  * Note that 'T&&' implicitly converts to 'T&'. So you can pass a 'T&&' to an
86  * ordinary copy constructor for a type that doesn't support a special move
87  * constructor, and you'll just get a copy. This means that templates can use
88  * Move whenever they know they won't use the original value any more, even if
89  * they're not sure whether the type at hand has a specialized move constructor.
90  * If it doesn't, the 'T&&' will just convert to a 'T&', and the ordinary copy
91  * constructor will apply.
92  *
93  * A class with a move constructor can also provide a move assignment operator.
94  * A generic definition would run this's destructor, and then apply the move
95  * constructor to *this's memory. A typical definition:
96  *
97  *   C& operator=(C&& rhs) {
98  *     MOZ_ASSERT(&rhs != this, "self-moves are prohibited");
99  *     this->~C();
100  *     new(this) C(Move(rhs));
101  *     return *this;
102  *   }
103  *
104  * With that in place, one can write move assignments like this:
105  *
106  *   c2 = Move(c1);
107  *
108  * This destroys c2, moves c1's value to c2, and leaves c1 in an undefined but
109  * destructible state.
110  *
111  * As we say, a move must leave the original in a "destructible" state. The
112  * original's destructor will still be called, so if a move doesn't
113  * actually steal all its resources, that's fine. We require only that the
114  * move destination must take on the original's value; and that destructing
115  * the original must not break the move destination.
116  *
117  * (Opinions differ on whether move assignment operators should deal with move
118  * assignment of an object onto itself. It seems wise to either handle that
119  * case, or assert that it does not occur.)
120  *
121  * Forwarding:
122  *
123  * Sometimes we want copy construction or assignment if we're passed an ordinary
124  * value, but move construction if passed an rvalue reference. For example, if
125  * our constructor takes two arguments and either could usefully be a move, it
126  * seems silly to write out all four combinations:
127  *
128  *   C::C(X&  x, Y&  y) : x(x),       y(y)       { }
129  *   C::C(X&  x, Y&& y) : x(x),       y(Move(y)) { }
130  *   C::C(X&& x, Y&  y) : x(Move(x)), y(y)       { }
131  *   C::C(X&& x, Y&& y) : x(Move(x)), y(Move(y)) { }
132  *
133  * To avoid this, C++11 has tweaks to make it possible to write what you mean.
134  * The four constructor overloads above can be written as one constructor
135  * template like so[0]:
136  *
137  *   template <typename XArg, typename YArg>
138  *   C::C(XArg&& x, YArg&& y) : x(Forward<XArg>(x)), y(Forward<YArg>(y)) { }
139  *
140  * ("'Don't Repeat Yourself'? What's that?")
141  *
142  * This takes advantage of two new rules in C++11:
143  *
144  * - First, when a function template takes an argument that is an rvalue
145  *   reference to a template argument (like 'XArg&& x' and 'YArg&& y' above),
146  *   then when the argument is applied to an lvalue, the template argument
147  *   resolves to 'T&'; and when it is applied to an rvalue, the template
148  *   argument resolves to 'T'. Thus, in a call to C::C like:
149  *
150  *      X foo(int);
151  *      Y yy;
152  *
153  *      C(foo(5), yy)
154  *
155  *   XArg would resolve to 'X', and YArg would resolve to 'Y&'.
156  *
157  * - Second, Whereas C++ used to forbid references to references, C++11 defines
158  *   'collapsing rules': 'T& &', 'T&& &', and 'T& &&' (that is, any combination
159  *   involving an lvalue reference) now collapse to simply 'T&'; and 'T&& &&'
160  *   collapses to 'T&&'.
161  *
162  *   Thus, in the call above, 'XArg&&' is 'X&&'; and 'YArg&&' is 'Y& &&', which
163  *   collapses to 'Y&'. Because the arguments are declared as rvalue references
164  *   to template arguments, the lvalue-ness "shines through" where present.
165  *
166  * Then, the 'Forward<T>' function --- you must invoke 'Forward' with its type
167  * argument --- returns an lvalue reference or an rvalue reference to its
168  * argument, depending on what T is. In our unified constructor definition, that
169  * means that we'll invoke either the copy or move constructors for x and y,
170  * depending on what we gave C's constructor. In our call, we'll move 'foo()'
171  * into 'x', but copy 'yy' into 'y'.
172  *
173  * This header file defines Move and Forward in the mozilla namespace. It's up
174  * to individual containers to annotate moves as such, by calling Move; and it's
175  * up to individual types to define move constructors and assignment operators
176  * when valuable.
177  *
178  * (C++11 says that the <utility> header file should define 'std::move' and
179  * 'std::forward', which are just like our 'Move' and 'Forward'; but those
180  * definitions aren't available in that header on all our platforms, so we
181  * define them ourselves here.)
182  *
183  * 0. This pattern is known as "perfect forwarding".  Interestingly, it is not
184  *    actually perfect, and it can't forward all possible argument expressions!
185  *    There is a C++11 issue: you can't form a reference to a bit-field.  As a
186  *    workaround, assign the bit-field to a local variable and use that:
187  *
188  *      // C is as above
189  *      struct S { int x : 1; } s;
190  *      C(s.x, 0); // BAD: s.x is a reference to a bit-field, can't form those
191  *      int tmp = s.x;
192  *      C(tmp, 0); // OK: tmp not a bit-field
193  */
194 
195 /**
196  * Identical to std::Move(); this is necessary until our stlport supports
197  * std::move().
198  */
199 template<typename T>
200 inline typename RemoveReference<T>::Type&&
Move(T && aX)201 Move(T&& aX)
202 {
203   return static_cast<typename RemoveReference<T>::Type&&>(aX);
204 }
205 
206 /**
207  * These two overloads are identical to std::forward(); they are necessary until
208  * our stlport supports std::forward().
209  */
210 template<typename T>
211 inline T&&
Forward(typename RemoveReference<T>::Type & aX)212 Forward(typename RemoveReference<T>::Type& aX)
213 {
214   return static_cast<T&&>(aX);
215 }
216 
217 template<typename T>
218 inline T&&
Forward(typename RemoveReference<T>::Type && aX)219 Forward(typename RemoveReference<T>::Type&& aX)
220 {
221   static_assert(!IsLvalueReference<T>::value,
222                 "misuse of Forward detected!  try the other overload");
223   return static_cast<T&&>(aX);
224 }
225 
226 /** Swap |aX| and |aY| using move-construction if possible. */
227 template<typename T>
228 inline void
Swap(T & aX,T & aY)229 Swap(T& aX, T& aY)
230 {
231   T tmp(Move(aX));
232   aX = Move(aY);
233   aY = Move(tmp);
234 }
235 
236 } // namespace mozilla
237 
238 #endif /* mozilla_Move_h */
239