标准库提供了若干基于复制的算法。其中一些,例如 std::copy
或 std::uninitialized_copy
,是容器和其他数据结构的基本构建块。该库为这些目的提供了基于移动的函数。
template<typename I, typename O> O move(I, I, O); template<typename I, typename O> O move_backward(I, I, O); template<typename I, typename F> F uninitialized_move(I, I, F); template<typename I, typename F> F uninitialized_copy_or_move(I, I, F);
前三个是其等效复制算法的移动变体,但复制赋值和复制构造被移动赋值和构造所取代。最后一个的行为与 std::uninitialized_copy
相同,但由于一些标准库实现与 move_iterator
不太兼容,因此此版本是愿意使用移动迭代器的用户的可移植版本。
#include "movable.hpp" #include <boost/move/algorithm.hpp> #include <cassert> #include <boost/aligned_storage.hpp> int main() { const std::size_t ArraySize = 10; movable movable_array[ArraySize]; movable movable_array2[ArraySize]; //move boost::move(&movable_array2[0], &movable_array2[ArraySize], &movable_array[0]); assert(movable_array2[0].moved()); assert(!movable_array[0].moved()); //move backward boost::move_backward(&movable_array[0], &movable_array[ArraySize], &movable_array2[ArraySize]); assert(movable_array[0].moved()); assert(!movable_array2[0].moved()); //uninitialized_move boost::aligned_storage< sizeof(movable)*ArraySize , boost::alignment_of<movable>::value>::type storage; movable *raw_movable = static_cast<movable*>(static_cast<void*>(&storage)); boost::uninitialized_move(&movable_array2[0], &movable_array2[ArraySize], raw_movable); assert(movable_array2[0].moved()); assert(!raw_movable[0].moved()); return 0; }