move.qbk 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. [/
  2. / Copyright (c) 2008-2010 Ion Gaztanaga
  3. /
  4. / Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. /]
  7. [library Boost.Move
  8. [quickbook 1.5]
  9. [authors [Gaztanaga, Ion]]
  10. [copyright 2008-2014 Ion Gaztanaga]
  11. [id move]
  12. [dirname move]
  13. [purpose Move semantics]
  14. [license
  15. Distributed under the Boost Software License, Version 1.0.
  16. (See accompanying file LICENSE_1_0.txt or copy at
  17. [@http://www.boost.org/LICENSE_1_0.txt])
  18. ]
  19. ]
  20. [important To be able to use containers of movable-only values in C++03 mode you will need to use containers
  21. supporting move semantics, like [*Boost.Container] containers]
  22. [section:tested_compilers Tested compilers]
  23. [*Boost.Move] has been tested in the following compilers/platforms:
  24. * Visual C++ >= 7.1.
  25. * GCC >= 4.1.
  26. [warning GCC < 4.3 and MSVC < 9.0 are deprecated and will be removed in the next version.]
  27. [endsect]
  28. [section:what_is_boost_move What is Boost.Move?]
  29. Rvalue references are a major C++0x feature, enabling move semantics for C++ values. However, we
  30. don't need C++0x compilers to take advantage of move semanatics. [*Boost.Move] emulates C++0x
  31. move semantics in C++03 compilers and allows writing portable code that works optimally in C++03
  32. and C++0x compilers.
  33. [endsect]
  34. [section:introduction Introduction]
  35. [note
  36. The first 3 chapters are the adapted from the article
  37. [@http://www.artima.com/cppsource/rvalue.html ['A Brief Introduction to Rvalue References]]
  38. by Howard E. Hinnant, Bjarne Stroustrup, and Bronek Kozicki
  39. ]
  40. Copying can be expensive. For example, for vectors `v2=v1` typically involves a function call,
  41. a memory allocation, and a loop. This is of course acceptable where we actually need two copies of
  42. a vector, but in many cases, we don't: We often copy a `vector` from one place to another, just to
  43. proceed to overwrite the old copy. Consider:
  44. [c++]
  45. template <class T> void swap(T& a, T& b)
  46. {
  47. T tmp(a); // now we have two copies of a
  48. a = b; // now we have two copies of b
  49. b = tmp; // now we have two copies of tmp (aka a)
  50. }
  51. But, we didn't want to have any copies of a or b, we just wanted to swap them. Let's try again:
  52. [c++]
  53. template <class T> void swap(T& a, T& b)
  54. {
  55. T tmp(::boost::move(a));
  56. a = ::boost::move(b);
  57. b = ::boost::move(tmp);
  58. }
  59. This `move()` gives its target the value of its argument, but is not obliged to preserve the value
  60. of its source. So, for a `vector`, `move()` could reasonably be expected to leave its argument as
  61. a zero-capacity vector to avoid having to copy all the elements. In other words, [*move is a potentially
  62. destructive copy].
  63. In this particular case, we could have optimized swap by a specialization. However, we can't
  64. specialize every function that copies a large object just before it deletes or overwrites it. That
  65. would be unmanageable.
  66. In C++0x, move semantics are implemented with the introduction of rvalue references. They allow us to
  67. implement `move()` without verbosity or runtime overhead. [*Boost.Move] is a library that offers tools
  68. to implement those move semantics not only in compilers with `rvalue references` but also in compilers
  69. conforming to C++03.
  70. [endsect]
  71. [section:implementing_movable_classes Implementing copyable and movable classes]
  72. [import ../example/doc_clone_ptr.cpp]
  73. [section:copyable_and_movable_cpp0x Copyable and movable classes in C++0x]
  74. Consider a simple handle class that owns a resource and also provides copy semantics
  75. (copy constructor and assignment). For example a `clone_ptr` might own a pointer, and call
  76. `clone()` on it for copying purposes:
  77. [c++]
  78. template <class T>
  79. class clone_ptr
  80. {
  81. private:
  82. T* ptr;
  83. public:
  84. // construction
  85. explicit clone_ptr(T* p = 0) : ptr(p) {}
  86. // destruction
  87. ~clone_ptr() { delete ptr; }
  88. // copy semantics
  89. clone_ptr(const clone_ptr& p)
  90. : ptr(p.ptr ? p.ptr->clone() : 0) {}
  91. clone_ptr& operator=(const clone_ptr& p)
  92. {
  93. if (this != &p)
  94. {
  95. T *p = p.ptr ? p.ptr->clone() : 0;
  96. delete ptr;
  97. ptr = p;
  98. }
  99. return *this;
  100. }
  101. // move semantics
  102. clone_ptr(clone_ptr&& p)
  103. : ptr(p.ptr) { p.ptr = 0; }
  104. clone_ptr& operator=(clone_ptr&& p)
  105. {
  106. if(this != &p)
  107. {
  108. std::swap(ptr, p.ptr);
  109. delete p.ptr;
  110. p.ptr = 0;
  111. }
  112. return *this;
  113. }
  114. // Other operations...
  115. };
  116. `clone_ptr` has expected copy constructor and assignment semantics, duplicating resources when copying.
  117. Note that copy constructing or assigning a `clone_ptr` is a relatively expensive operation:
  118. [copy_clone_ptr]
  119. `clone_ptr` is code that you might find in today's books on C++, except for the part marked as
  120. `move semantics`. That part is implemented in terms of C++0x `rvalue references`. You can find
  121. some good introduction and tutorials on rvalue references in these papers:
  122. * [@http://www.artima.com/cppsource/rvalue.html ['A Brief Introduction to Rvalue References]]
  123. * [@http://blogs.msdn.com/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx ['Rvalue References: C++0x Features in VC10, Part 2]]
  124. When the source of the copy is known to be a `rvalue` (e.g.: a temporary object), one can avoid the
  125. potentially expensive `clone()` operation by pilfering source's pointer (no one will notice!). The move
  126. constructor above does exactly that, leaving the rvalue in a default constructed state. The move assignment
  127. operator simply does the same freeing old resources.
  128. Now when code tries to copy a rvalue `clone_ptr`, or if that code explicitly gives permission to
  129. consider the source of the copy a rvalue (using `boost::move`), the operation will execute much faster.
  130. [move_clone_ptr]
  131. [endsect]
  132. [section:copyable_and_movable_cpp03 Copyable and movable classes in portable syntax for both C++03 and C++0x compilers]
  133. Many aspects of move semantics can be emulated for compilers not supporting `rvalue references`
  134. and [*Boost.Move] offers tools for that purpose. With [*Boost.Move] we can write `clone_ptr`
  135. so that it will work both in compilers with rvalue references and those who conform to C++03.
  136. You just need to follow these simple steps:
  137. * Put the following macro in the [*private] section:
  138. [macroref BOOST_COPYABLE_AND_MOVABLE BOOST_COPYABLE_AND_MOVABLE(classname)]
  139. * Leave copy constructor as is.
  140. * Write a copy assignment taking the parameter as
  141. [macroref BOOST_COPY_ASSIGN_REF BOOST_COPY_ASSIGN_REF(classname)]
  142. * Write a move constructor and a move assignment taking the parameter as
  143. [macroref BOOST_RV_REF BOOST_RV_REF(classname)]
  144. Let's see how are applied to `clone_ptr`:
  145. [clone_ptr_def]
  146. [endsect]
  147. [*Question]: What about types that don't own resources? (E.g. `std::complex`?)
  148. No work needs to be done in that case. The copy constructor is already optimal.
  149. [endsect]
  150. [section:composition_inheritance Composition or inheritance]
  151. For classes made up of other classes (via either composition or inheritance), the move constructor
  152. and move assignment can be easily coded using the `boost::move` function:
  153. [clone_ptr_base_derived]
  154. [important Due to limitations in the emulation code, a cast to `Base &` is needed before moving the base part in the move
  155. constructor and call Base's move constructor instead of the copy constructor.]
  156. Each subobject will now be treated individually, calling move to bind to the subobject's move
  157. constructors and move assignment operators. `Member` has move operations coded (just like
  158. our earlier `clone_ptr` example) which will completely avoid the tremendously more expensive
  159. copy operations:
  160. [clone_ptr_move_derived]
  161. Note above that the argument x is treated as a lvalue reference. That's why it is necessary to
  162. say `move(x)` instead of just x when passing down to the base class. This is a key safety feature of move
  163. semantics designed to prevent accidently moving twice from some named variable. All moves from
  164. lvalues occur explicitly.
  165. [endsect]
  166. [section:movable_only_classes Movable but Non-Copyable Types]
  167. Some types are not amenable to copy semantics but can still be made movable. For example:
  168. * `unique_ptr` (non-shared, non-copyable ownership)
  169. * A type representing a thread of execution
  170. * A type representing a file descriptor
  171. By making such types movable (though still non-copyable) their utility is tremendously
  172. increased. Movable but non-copyable types can be returned by value from factory functions:
  173. [c++]
  174. file_descriptor create_file(/* ... */);
  175. //...
  176. file_descriptor data_file;
  177. //...
  178. data_file = create_file(/* ... */); // No copies!
  179. In the above example, the underlying file handle is passed from object to object, as long
  180. as the source `file_descriptor` is a rvalue. At all times, there is still only one underlying file
  181. handle, and only one `file_descriptor` owns it at a time.
  182. To write a movable but not copyable type in portable syntax, you need to follow these simple steps:
  183. * Put the following macro in the [*private] section:
  184. [macroref BOOST_MOVABLE_BUT_NOT_COPYABLE BOOST_MOVABLE_BUT_NOT_COPYABLE(classname)]
  185. * Write a move constructor and a move assignment taking the parameter as
  186. [macroref BOOST_RV_REF BOOST_RV_REF(classname)]
  187. Here's the definition of `file descriptor` using portable syntax:
  188. [import ../example/doc_file_descriptor.cpp]
  189. [file_descriptor_def]
  190. [/
  191. /Many standard algorithms benefit from moving elements of the sequence as opposed to
  192. /copying them. This not only provides better performance (like the improved `swap`
  193. /implementation described above), but also allows these algorithms to operate on movable
  194. /but non-copyable types. For example the following code sorts a `vector<unique_ptr<T>>`
  195. /based on comparing the pointed-to types:
  196. /
  197. /[c++]
  198. /
  199. / struct indirect_less
  200. / {
  201. / template <class T>
  202. / bool operator()(const T& x, const T& y)
  203. / {return *x < *y;}
  204. / };
  205. / ...
  206. / std::vector<std::unique_ptr<A>> v;
  207. / ...
  208. / std::sort(v.begin(), v.end(), indirect_less());
  209. /
  210. /
  211. /As sort moves the unique_ptr's around, it will use swap (which no longer requires Copyability)
  212. /or move construction / move assignment. Thus during the entire algorithm, the invariant that
  213. /each item is owned and referenced by one and only one smart pointer is maintained. If the
  214. /algorithm were to attempt a copy (say by programming mistake) a compile time error would result.
  215. /]
  216. [endsect]
  217. [section:move_and_containers Containers and move semantics]
  218. Movable but non-copyable types can be safely inserted into containers and
  219. movable and copyable types are more efficiently handled if those containers
  220. internally use move semantics instead of copy semantics.
  221. If the container needs to "change the location" of an element
  222. internally (e.g. vector reallocation) it will move the element instead of copying it.
  223. [*Boost.Container] containers are move-aware so you can write the following:
  224. [file_descriptor_example]
  225. [endsect]
  226. [section:construct_forwarding Constructor Forwarding]
  227. Consider writing a generic factory function that returns an object for a newly
  228. constructed generic type. Factory functions such as this are valuable for encapsulating
  229. and localizing the allocation of resources. Obviously, the factory function must accept
  230. exactly the same sets of arguments as the constructors of the type of objects constructed:
  231. [c++]
  232. template<class T> T* factory_new()
  233. { return new T(); }
  234. template<class T> T* factory_new(a1)
  235. { return new T(a1); }
  236. template<class T> T* factory_new(a1, a2)
  237. { return new T(a1, a2); }
  238. Unfortunately, in C++03 the much bigger issue with this approach is that the N-argument case
  239. would require 2^N overloads, immediately discounting this as a general solution. Fortunately,
  240. most constructors take arguments by value, by const-reference or by rvalue reference. If these
  241. limitations are accepted, the forwarding emulation of a N-argument case requires just N overloads.
  242. This library makes this emulation easy with the help of `BOOST_FWD_REF` and
  243. `boost::forward`:
  244. [import ../example/doc_construct_forward.cpp]
  245. [construct_forward_example]
  246. Constructor forwarding comes in handy to implement placement insertion in containers with
  247. just N overloads if the implementor accepts the limitations of this type of forwarding for
  248. C++03 compilers. In compilers with rvalue references perfect forwarding is achieved.
  249. [endsect]
  250. [section:move_return Implicit Move when returning a local object]
  251. The C++ standard specifies situations where an implicit move operation is safe and the
  252. compiler can use it in cases were the (Named) Return Value Optimization) can't be used.
  253. The typical use case is when a function returns a named (non-temporary) object by value
  254. and the following code will perfectly compile in C++11:
  255. [c++]
  256. //Even if movable can't be copied
  257. //the compiler will call the move-constructor
  258. //to generate the return value
  259. //
  260. //The compiler can also optimize out the move
  261. //and directly construct the object 'm'
  262. movable factory()
  263. {
  264. movable tmp;
  265. m = ...
  266. //(1) moved instead of copied
  267. return tmp;
  268. };
  269. //Initialize object
  270. movable m(factory());
  271. In compilers without rvalue references and some non-conforming compilers (such as Visual C++ 2010/2012)
  272. the line marked with `(1)` would trigger a compilation error because `movable` can't be copied. Using a explicit
  273. `::boost::move(tmp)` would workaround this limitation but it would code suboptimal in C++11 compilers
  274. (as the compile could not use (N)RVO to optimize-away the copy/move).
  275. [*Boost.Move] offers an additional macro called [macroref BOOST_MOVE_RET BOOST_MOVE_RET] that can be used to
  276. alleviate this problem obtaining portable move-on-return semantics. Let's use the previously presented
  277. movable-only `movable` class with classes `copyable` (copy-only type), `copy_movable` (can be copied and moved) and
  278. `non_copy_movable` (non-copyable and non-movable):
  279. [import ../example/copymovable.hpp]
  280. [copy_movable_definition]
  281. and build a generic factory function that returns a newly constructed value or a reference to an already
  282. constructed object.
  283. [import ../example/doc_move_return.cpp]
  284. [move_return_example]
  285. [*Caution]: When using this macro in a non-conforming or C++03
  286. compilers, a move will be performed even if the C++11 standard does not allow it
  287. (e.g. returning a static variable). The user is responsible for using this macro
  288. only used to return local objects that met C++11 criteria. E.g.:
  289. [c++]
  290. struct foo
  291. {
  292. copy_movable operator()() const
  293. {
  294. //ERROR! The Standard does not allow implicit move returns when the object to be returned
  295. //does not met the criteria for elision of a copy operation (such as returning a static member data)
  296. //In C++03 compilers this will MOVE resources from cm
  297. //In C++11 compilers this will COPY resources from cm
  298. //so DON'T use use BOOST_MOVE_RET without care.
  299. return BOOST_MOVE_RET(copy_movable, cm);
  300. }
  301. static copy_movable cm;
  302. };
  303. [*Note]: When returning a temporary object `BOOST_MOVE_REF` is not needed as copy ellision rules will work on
  304. both C++03 and C++11 compilers.
  305. [c++]
  306. //Note: no BOOST_MOVE_RET
  307. movable get_movable()
  308. { return movable(); }
  309. copy_movable get_copy_movable()
  310. { return copy_movable(); }
  311. copyable get_copyable()
  312. { return copyable(); }
  313. [endsect]
  314. [section:move_iterator Move iterators]
  315. [c++]
  316. template<class Iterator>
  317. class move_iterator;
  318. template<class It>
  319. move_iterator<It> make_move_iterator(const It &it);
  320. [classref boost::move_iterator move_iterator] is an iterator adaptor with the
  321. same behavior as the underlying iterator
  322. except that its dereference operator implicitly converts the value returned by the
  323. underlying iterator's dereference operator to a rvalue reference: `boost::move(*underlying_iterator)`
  324. It is a read-once iterator, but can have up to random access traversal characteristics.
  325. `move_iterator` is very useful because some generic algorithms and container insertion functions
  326. can be called with move iterators to replace copying with moving. For example:
  327. [import ../example/movable.hpp]
  328. [movable_definition]
  329. `movable` objects can be moved from one container to another using move iterators and insertion
  330. and assignment operations.w
  331. [import ../example/doc_move_iterator.cpp]
  332. [move_iterator_example]
  333. [endsect]
  334. [section:move_inserters Move inserters]
  335. Similar to standard insert iterators, it's possible to deal with move insertion in the same way
  336. as writing into an array. A special kind of iterator adaptors, called move insert iterators, are
  337. provided with this library. With regular iterator classes,
  338. [c++]
  339. while (first != last) *result++ = *first++;
  340. causes a range [first,last) to be copied into a range starting with result. The same code with
  341. result being a move insert iterator will move insert corresponding elements into the container.
  342. This device allows all of the copying algorithms in the library to work in the move insert mode
  343. instead of the regular overwrite mode. This library offers 3 move insert iterators and their
  344. helper functions:
  345. [c++]
  346. // Note: C models Container
  347. template <typename C>
  348. class back_move_insert_iterator;
  349. template <typename C>
  350. back_move_insert_iterator<C> back_move_inserter(C& x);
  351. template <typename C>
  352. class front_move_insert_iterator;
  353. template <typename C>
  354. front_move_insert_iterator<C> front_move_inserter(C& x);
  355. template <typename C>
  356. class move_insert_iterator;
  357. template <typename C>
  358. move_insert_iterator<C> move_inserter(C& x, typename C::iterator it);
  359. A move insert iterator is constructed from a container and possibly one of its iterators pointing
  360. to where insertion takes place if it is neither at the beginning nor at the end of the container.
  361. Insert iterators satisfy the requirements of output iterators. `operator*` returns the move insert
  362. iterator itself. The assignment `operator=(T& x)` is defined on insert iterators to allow writing
  363. into them, it inserts x right before where the insert iterator is pointing. In other words, an
  364. `insert iterator` is like a cursor pointing into the container where the insertion takes place.
  365. `back_move_iterator` move inserts elements at the end of a container, `front_insert_iterator`
  366. move inserts elements at the beginning of a container, and `move_insert_iterator` move inserts
  367. elements where the iterator points to in a container. `back_move_inserter`, `front_move_inserter`,
  368. and `move_inserter` are three functions making the insert iterators out of a container. Here's
  369. an example of how to use them:
  370. [import ../example/doc_move_inserter.cpp]
  371. [move_inserter_example]
  372. [endsect]
  373. [section:move_algorithms Move algorithms]
  374. The standard library offers several copy-based algorithms. Some of them, like `std::copy` or
  375. `std::uninitialized_copy` are basic building blocks for containers and other data structures.
  376. This library offers move-based functions for those purposes:
  377. [c++]
  378. template<typename I, typename O> O move(I, I, O);
  379. template<typename I, typename O> O move_backward(I, I, O);
  380. template<typename I, typename F> F uninitialized_move(I, I, F);
  381. template<typename I, typename F> F uninitialized_copy_or_move(I, I, F);
  382. The first 3 are move variations of their equivalent copy algorithms, but copy assignment and
  383. copy construction are replaced with move assignment and construction. The last one has the
  384. same behaviour as `std::uninitialized_copy` but since several standand library implementations
  385. don't play very well with `move_iterator`s, this version is a portable version for those
  386. willing to use move iterators.
  387. [import ../example/doc_move_algorithms.cpp]
  388. [move_algorithms_example]
  389. [endsect]
  390. [section:emulation_limitations Emulation limitations]
  391. Like any emulation effort, the library has some limitations users should take in
  392. care to achieve portable and efficient code when using the library with C++03 conformant compilers:
  393. [section:emulation_limitations_base Initializing base classes]
  394. When initializing base classes in move constructors, users must
  395. cast the reference to a base class reference before moving it or just
  396. use `BOOST_MOVE_BASE`. Example:
  397. [c++]
  398. Derived(BOOST_RV_REF(Derived) x) // Move ctor
  399. : Base(boost::move(static_cast<Base&>(x)))
  400. //...
  401. or
  402. [c++]
  403. Derived(BOOST_RV_REF(Derived) x) // Move ctor
  404. : Base(BOOST_MOVE_BASE(Base, x))
  405. //...
  406. If casting is not performed the emulation will not move construct
  407. the base class, because no conversion is available from `BOOST_RV_REF(Derived)` to
  408. `BOOST_RV_REF(Base)`. Without the cast or `BOOST_MOVE_BASE` we might obtain a compilation
  409. error (for non-copyable types) or a less-efficient move constructor (for copyable types):
  410. [c++]
  411. //If Derived is copyable, then Base is copy-constructed.
  412. //If not, a compilation error is issued
  413. Derived(BOOST_RV_REF(Derived) x) // Move ctor
  414. : Base(boost::move(x))
  415. //...
  416. [endsect]
  417. [section:template_parameters Template parameters for perfect forwarding]
  418. The emulation can't deal with C++0x reference collapsing rules that allow perfect forwarding:
  419. [c++]
  420. //C++0x
  421. template<class T>
  422. void forward_function(T &&t)
  423. { inner_function(std::forward<T>(t); }
  424. //Wrong C++03 emulation
  425. template<class T>
  426. void forward_function(BOOST_RV_REF<T> t)
  427. { inner_function(boost::forward<T>(t); }
  428. In C++03 emulation BOOST_RV_REF doesn't catch any const rlvalues. For more details on
  429. forwarding see [link move.construct_forwarding Constructor Forwarding] chapter.
  430. [endsect]
  431. [section:emulation_limitations_binding Binding of rvalue references to lvalues]
  432. The
  433. [@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1690.html first rvalue reference]
  434. proposal allowed the binding of rvalue references to lvalues:
  435. [c++]
  436. func(Type &&t);
  437. //....
  438. Type t; //Allowed
  439. func(t)
  440. Later, as explained in
  441. [@http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2812.html ['Fixing a Safety Problem with Rvalue References]]
  442. this behaviour was considered dangerous and eliminated this binding so that rvalue references adhere to the
  443. principle of type-safe overloading: ['Every function must be type-safe in isolation, without regard to how it has been overloaded]
  444. [*Boost.Move] can't emulate this type-safe overloading principle for C++03 compilers:
  445. [c++]
  446. //Allowed by move emulation
  447. movable m;
  448. BOOST_RV_REF(movable) r = m;
  449. [endsect]
  450. [section:assignment_operator Assignment operator in classes derived from or holding copyable and movable types]
  451. The macro [macroref BOOST_COPYABLE_AND_MOVABLE BOOST_COPYABLE_AND_MOVABLE] needs to
  452. define a copy constructor for `copyable_and_movable` taking a non-const parameter in C++03 compilers:
  453. [c++]
  454. //Generated by BOOST_COPYABLE_AND_MOVABLE
  455. copyable_and_movable &operator=(copyable_and_movable&){/**/}
  456. Since the non-const overload of the copy constructor is generated, compiler-generated
  457. assignment operators for classes containing `copyable_and_movable`
  458. will get the non-const copy constructor overload, which will surely surprise users:
  459. [c++]
  460. class holder
  461. {
  462. copyable_and_movable c;
  463. };
  464. void func(const holder& h)
  465. {
  466. holder copy_h(h); //<--- ERROR: can't convert 'const holder&' to 'holder&'
  467. //Compiler-generated copy constructor is non-const:
  468. // holder& operator(holder &)
  469. //!!!
  470. }
  471. This limitation forces the user to define a const version of the copy assignment,
  472. in all classes holding copyable and movable classes which might be annoying in some cases.
  473. An alternative is to implement a single `operator =()` for copyable and movable classes
  474. [@http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/ using "pass by value" semantics]:
  475. [c++]
  476. T& operator=(T x) // x is a copy of the source; hard work already done
  477. {
  478. swap(*this, x); // trade our resources for x's
  479. return *this; // our (old) resources get destroyed with x
  480. }
  481. However, "pass by value" is not optimal for classes (like containers, strings, etc.) that reuse resources
  482. (like previously allocated memory) when x is assigned from a lvalue.
  483. [endsect]
  484. [section:templated_assignment_operator Templated assignment operator in copyable and movable types]
  485. [import ../example/doc_template_assign.cpp]
  486. Given a movable and copyable class, if a templated assignment operator (*) is added:
  487. [template_assign_example_foo_bar]
  488. C++98 and C++11 compilers will behave different when assigning from a `[const] Foo` lvalue:
  489. [template_assign_example_main]
  490. This different behaviour is a side-effect of the move emulation that can't be easily avoided by
  491. [*Boost.Move]. One workaround is to SFINAE-out the templated assignment operator with `disable_if`:
  492. [c++]
  493. template<class U> // Modified templated assignment
  494. typename boost::disable_if<boost::is_same<U, Foo>, Foo&>::type
  495. operator=(const U& rhs)
  496. { i = -rhs.i; return *this; } //(2)
  497. [endsect]
  498. [endsect]
  499. [section:how_the_library_works How the library works]
  500. [*Boost.Move] is based on macros that are expanded to true rvalue references in C++0x compilers
  501. and emulated rvalue reference classes and conversion operators in C++03 compilers.
  502. In C++03 compilers [*Boost.Move] defines a class named `::boost::rv`:
  503. [c++]
  504. template <class T>
  505. class rv : public T
  506. {
  507. rv();
  508. ~rv();
  509. rv(rv const&);
  510. void operator=(rv const&);
  511. };
  512. which is convertible to the movable base class (usual C++ derived to base conversion). When users mark
  513. their classes as [macroref BOOST_MOVABLE_BUT_NOT_COPYABLE BOOST_MOVABLE_BUT_NOT_COPYABLE] or
  514. [macroref BOOST_COPYABLE_AND_MOVABLE BOOST_COPYABLE_AND_MOVABLE], these macros define conversion
  515. operators to references to `::boost::rv`:
  516. [c++]
  517. #define BOOST_MOVABLE_BUT_NOT_COPYABLE(TYPE)\
  518. public:\
  519. operator ::boost::rv<TYPE>&() \
  520. { return *static_cast< ::boost::rv<TYPE>* >(this); }\
  521. operator const ::boost::rv<TYPE>&() const \
  522. { return static_cast<const ::boost::rv<TYPE>* >(this); }\
  523. private:\
  524. //More stuff...
  525. [macroref BOOST_MOVABLE_BUT_NOT_COPYABLE BOOST_MOVABLE_BUT_NOT_COPYABLE] also declares a
  526. private copy constructor and assignment. [macroref BOOST_COPYABLE_AND_MOVABLE BOOST_COPYABLE_AND_MOVABLE]
  527. defines a non-const copy constructor `TYPE &operator=(TYPE&)` that forwards to a const version:
  528. #define BOOST_COPYABLE_AND_MOVABLE(TYPE)\
  529. public:\
  530. TYPE& operator=(TYPE &t)\
  531. { this->operator=(static_cast<const ::boost::rv<TYPE> &>(const_cast<const TYPE &>(t))); return *this;}\
  532. //More stuff...
  533. In C++0x compilers `BOOST_COPYABLE_AND_MOVABLE` expands to nothing and `BOOST_MOVABLE_BUT_NOT_COPYABLE`
  534. declares copy constructor and assigment operator private.
  535. When users define the [macroref BOOST_RV_REF BOOST_RV_REF] overload of a copy constructor/assignment, in
  536. C++0x compilers it is expanded to a rvalue reference (`T&&`) overload and in C++03 compilers it is expanded
  537. to a `::boost::rv<T> &` overload:
  538. [c++]
  539. #define BOOST_RV_REF(TYPE) ::boost::rv< TYPE >& \
  540. When users define the [macroref BOOST_COPY_ASSIGN_REF BOOST_COPY_ASSIGN_REF] overload,
  541. it is expanded to a usual copy assignment (`const T &`) overload in C++0x compilers and
  542. to a `const ::boost::rv &` overload in C++03 compilers:
  543. [c++]
  544. #define BOOST_COPY_ASSIGN_REF(TYPE) const ::boost::rv< TYPE >&
  545. As seen, in [*Boost.Move] generates efficient and clean code for C++0x move
  546. semantics, without modifying any resolution overload. For C++03 compilers
  547. when overload resolution is performed these are the bindings:
  548. * a) non-const rvalues (e.g.: temporaries), bind to `::boost::rv< TYPE >&`
  549. * b) const rvalue and lvalues, bind to `const ::boost::rv< TYPE >&`
  550. * c) non-const lvalues (e.g. non-const references) bind to `TYPE&`
  551. The library does not define the equivalent of
  552. [macroref BOOST_COPY_ASSIGN_REF BOOST_COPY_ASSIGN_REF] for copy construction (say, `BOOST_COPY_CTOR_REF`)
  553. because nearly all modern compilers implement RVO and this is much more efficient than any move emulation.
  554. [funcref boost::move move] just casts `TYPE &` into `::boost::rv<TYPE> &`.
  555. Here's an example that demostrates how different rlvalue objects bind to `::boost::rv` references in the
  556. presence of three overloads and the conversion operators in C++03 compilers:
  557. [import ../example/doc_how_works.cpp]
  558. [how_works_example]
  559. [endsect]
  560. [section:thanks_to Thanks and credits]
  561. Thanks to all that developed ideas for move emulation: the first emulation was based on Howard Hinnant
  562. emulation code for `unique_ptr`, David Abrahams suggested the use of `class rv`,
  563. and Klaus Triendl discovered how to bind const rlvalues using `class rv`.
  564. Many thanks to all boosters that have tested, reviewed and improved the library.
  565. Special thanks to:
  566. * Orson Peters, author of [@https://github.com/orlp/pdqsort Pattern-defeating quicksort (pdqsort)].
  567. * Andrey Astrelin, author of [@https://github.com/Mrrl/GrailSort Grail Sort].
  568. [endsect]
  569. [section:release_notes Release Notes]
  570. [section:release_notes_boost_1_71 Boost 1.71 Release]
  571. * Fixed bugs:
  572. * [@https://github.com/boostorg/move/issues/26 Git Issue #26: ['"Invalid iterator increment/decrement in the last iteration of adaptive_sort_combine_blocks"]].
  573. [endsect]
  574. [section:release_notes_boost_1_70 Boost 1.70 Release]
  575. * Removed support for deprecated GCC compilers.
  576. * Fixed bugs:
  577. * [@https://github.com/boostorg/move/pull/23 Git Pull #23: ['"Add minimal cmake file"]].
  578. * [@https://github.com/boostorg/move/issues/25 Git Issue #25: ['"adaptive_merge is broken for iterator_traits<RandIt>::size_type != std::size_t"]].
  579. [endsect]
  580. [section:release_notes_boost_1_69 Boost 1.69 Release]
  581. * Deprecated GCC < 4.3 and MSVC < 9.0 (Visual 2008) compilers.
  582. * Fixed bugs:
  583. * [@https://github.com/boostorg/move/issues/15 Git Issue #19: ['"Compilation error with IBM xlC++ on AIX"]].
  584. [endsect]
  585. [section:release_notes_boost_1_67 Boost 1.67 Release]
  586. * Added pdqsort and heap_sort implementations, initially as a detail, they will be official in the future once better tested.
  587. [endsect]
  588. [section:release_notes_boost_1_66 Boost 1.66 Release]
  589. * Fixed bugs:
  590. * [@https://github.com/boostorg/move/pull/14 Git Pull #14: ['"Workaround for bogus [-Wignored-attributes] warning on GCC 6.x/7.x"]].
  591. * [@https://github.com/boostorg/move/issues/15 Git Issue #15: ['"Incorrect merge in adaptive_merge when the number of unique items is limited"]].
  592. [endsect]
  593. [section:release_notes_boost_1_65 Boost 1.65 Release]
  594. * Fixed bug:
  595. * [@https://github.com/boostorg/move/pull/11 Git Pull #11: ['"replace 'std::random_shuffle' by '::random_shuffle'"]].
  596. * [@https://github.com/boostorg/move/pull/12 Git Pull #12: ['"Adds support for MSVC ARM64 target'"]].
  597. [endsect]
  598. [section:release_notes_boost_1_64 Boost 1.64 Release]
  599. * Fixed bug:
  600. * [@https://svn.boost.org/trac/boost/ticket/12920 #12920 ['"movelib::unique_ptr: incorrect pointer type for nested array"]].
  601. [endsect]
  602. [section:release_notes_boost_1_62 Boost 1.62 Release]
  603. * Documented new limitations reported in Trac tickets
  604. [@https://svn.boost.org/trac/boost/ticket/12194 #12194 ['"Copy assignment on moveable and copyable classes uses wrong type"]] and
  605. [@https://svn.boost.org/trac/boost/ticket/12307 #12307 ['"Copy assignment from const ref handled differently in C++11/C++98"]].
  606. [endsect]
  607. [section:release_notes_boost_1_61 Boost 1.61 Release]
  608. * Experimental: asymptotically optimal bufferless merge and sort algorithms: [funcref boost::movelib::adaptive_merge adaptive_merge]
  609. and [funcref boost::movelib::adaptive_sort adaptive_sort].
  610. * Fixed bug:
  611. * [@https://svn.boost.org/trac/boost/ticket/11758 Trac #11758: ['"BOOST_MOVABLE_BUT_NOT_COPYABLE doesn't reset private access with rvalue ref version"]],
  612. [endsect]
  613. [section:release_notes_boost_1_60 Boost 1.60 Release]
  614. * Fixed bug:
  615. * [@https://svn.boost.org/trac/boost/ticket/11615 Trac #11615: ['"Boost.Move should use the qualified name for std::size_t in type_traits.hpp"]],
  616. [endsect]
  617. [section:release_notes_boost_1_59 Boost 1.59 Release]
  618. * Changed `unique_ptr`'s converting constructor taking the source by value in C++03 compilers to allow simple conversions
  619. from convertible types returned by value.
  620. * Fixed bug:
  621. * [@https://svn.boost.org/trac/boost/ticket/11229 Trac #11229: ['"vector incorrectly copies move-only objects using memcpy"]],
  622. * [@https://svn.boost.org/trac/boost/ticket/11510 Trac #11510: ['"unique_ptr: -Wshadow warning issued"]],
  623. [endsect]
  624. [section:release_notes_boost_1_58_00 Boost 1.58 Release]
  625. * Added [macroref BOOST_MOVE_BASE BOOST_MOVE_BASE] utility.
  626. * Added [funcref boost::adl_move_swap adl_move_swap] utility.
  627. * Reduced dependencies on other Boost libraries to make the library a bit more lightweight.
  628. * Fixed bugs:
  629. * [@https://svn.boost.org/trac/boost/ticket/11044 Trac #11044: ['"boost::rv inherits off union, when such passed as template argument"]].
  630. [endsect]
  631. [section:release_notes_boost_1_57_00 Boost 1.57 Release]
  632. * Added `unique_ptr` smart pointer. Thanks to Howard Hinnant for his excellent unique_ptr emulation code and testsuite.
  633. * Added `move_if_noexcept` utility. Thanks to Antony Polukhin for the implementation.
  634. * Fixed bugs:
  635. * [@https://svn.boost.org/trac/boost/ticket/9785 Trac #9785: ['"Compiler warning with intel icc in boost/move/core.hpp"]],
  636. * [@https://svn.boost.org/trac/boost/ticket/10460 Trac #10460: ['"Compiler error due to looser throw specifier"]],
  637. * [@https://github.com/boostorg/move/pull/3 Git Pull #3: ['"Don't delete copy constructor when rvalue references are disabled"]],
  638. [endsect]
  639. [section:release_notes_boost_1_56_00 Boost 1.56 Release]
  640. * Added [macroref BOOST_MOVE_RET BOOST_MOVE_RET].
  641. * Fixed bugs:
  642. * [@https://svn.boost.org/trac/boost/ticket/9482 #9482: ['"MSVC macros not undefined in boost/move/detail/config_end.hpp"]],
  643. * [@https://svn.boost.org/trac/boost/ticket/9045 #9045: ['"Wrong macro name on docs"]],
  644. * [@https://svn.boost.org/trac/boost/ticket/8420 #8420: ['"move's is_convertible does not compile with aligned data"]].
  645. [endsect]
  646. [section:release_notes_boost_1_55_00 Boost 1.55 Release]
  647. * Fixed bugs [@https://svn.boost.org/trac/boost/ticket/7952 #7952],
  648. [@https://svn.boost.org/trac/boost/ticket/8764 #8764],
  649. [@https://svn.boost.org/trac/boost/ticket/8765 #8765],
  650. [@https://svn.boost.org/trac/boost/ticket/8842 #8842],
  651. [@https://svn.boost.org/trac/boost/ticket/8979 #8979].
  652. [endsect]
  653. [section:release_notes_boost_1_54_00 Boost 1.54 Release]
  654. * Fixed bugs [@https://svn.boost.org/trac/boost/ticket/7969 #7969],
  655. [@https://svn.boost.org/trac/boost/ticket/8231 #8231],
  656. [@https://svn.boost.org/trac/boost/ticket/8765 #8765].
  657. [endsect]
  658. [section:release_notes_boost_1_53_00 Boost 1.53 Release]
  659. * Better header segregation (bug
  660. [@https://svn.boost.org/trac/boost/ticket/6524 #6524]).
  661. * Small documentation fixes
  662. * Replaced deprecated BOOST_NO_XXXX with newer BOOST_NO_CXX11_XXX macros.
  663. * Fixed [@https://svn.boost.org/trac/boost/ticket/7830 #7830],
  664. [@https://svn.boost.org/trac/boost/ticket/7832 #7832].
  665. [endsect]
  666. [section:release_notes_boost_1_51_00 Boost 1.51 Release]
  667. * Fixed bugs
  668. [@https://svn.boost.org/trac/boost/ticket/7095 #7095],
  669. [@https://svn.boost.org/trac/boost/ticket/7031 #7031].
  670. [endsect]
  671. [section:release_notes_boost_1_49_00 Boost 1.49 Release]
  672. * Fixed bugs
  673. [@https://svn.boost.org/trac/boost/ticket/6417 #6417],
  674. [@https://svn.boost.org/trac/boost/ticket/6183 #6183],
  675. [@https://svn.boost.org/trac/boost/ticket/6185 #6185],
  676. [@https://svn.boost.org/trac/boost/ticket/6395 #6395],
  677. [@https://svn.boost.org/trac/boost/ticket/6396 #6396],
  678. [endsect]
  679. [endsect]
  680. [xinclude autodoc.xml]