Move.h 9.5 KB

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