boost中移动语义的支持

来源:互联网 发布:视频照片制作软件 编辑:程序博客网 时间:2024/05/20 14:40

移动拷贝语义支持 编写步骤:

1. 将BOOST_COPYABLE_AND_MOVABLE(classname)写到类的私有区域;

2. 重载operator= 参数为BOOST_COPY_ASSIGN_REF(classname) 此赋值操作为平时写的operator=;

3. 重载拷贝构造函数与operator=参数为BOOST_RV_REF(classname) move的构造拷贝语operator=

当想使用移动语义时, 使用boost::move()进行参数传递


#include <boost/move/utility.hpp>

class Base

{

public:

Base();

Base(const Base& x);

Base(BOOST_RV_REF(Base) x);

Base& operator=(BOOST_RV_REF(Base) x); //move operator=

Base& operator=(BOOST_COPY_ASSIGN_REF(Base) x); //normal operator=

private:

BOOST_COPYABLE_AND_MOVABLE(Base);

};

class Derived : public Base

{

public:

        Derived();

Derived(BOOST_RV_REF(Derived) x) : Base(boost::move(static_cast<Base&>(x){}

Derived& operator=(BOOST_RV_REF(Derived) x)

{

Base::operator=(boost::move(static_cast<Base&>(x)));

return *this;

}

Derived& operator=(BOOST_COPY_ASSIGN_REF(Derived) x)

{

Base::operator=(static_cast<const Base&>(x));

return *this;

}

private:

BOOST_COPYABLE_AND_MOVABLE(Derived);

};

注意 static_cast<Base&>(x)的使用


移动不拷贝语义:

1. 在类中私有区域书写BOOST_MOVABLE_BUT_COPYABLE(classname);

2. 写一个移动构造与operator= 参数类型为BOOST_RV_REF(classname);


boost::container容器支持与移动语义:

#include <boost/container/vector.hpp>

boost::container::vector<object> vec;

vec.push_back(boost::move(var));


move迭代器:

#include <boost/container/vector.hpp>

vector<movable> v(10);

vector<movable> v2(boost::make_move_iterator(v.begin()), boost::make_move_iterator(v.end()));


移动插入迭代器 C代表一个容器:

template <typename C>

back_move_insert_iterator<C> back_move_inserter(C& x);

front_move_insert_iterator<C> front_move_inserter(C& x);

move_insert_iterator<C> move_inserter(C& x, typename C::iterator it);


算法:

 move算法 类似于copy算法:

template<typename I, typename O> O move(I, I, O);

template<typename I, typename O> O move_backward(I, I, O);





0 0
原创粉丝点击