C++容器与noncopyable

来源:互联网 发布:网络教育是怎么回事 编辑:程序博客网 时间:2024/05/16 10:28

容器需要有复制语义因此,不能直接使用vector去存储noncopyable对象.

这个时候就需要移动语义:

#include <iostream>#include <vector>#include <boost/noncopyable.hpp>class A : boost::noncopyable{    public:        A()=default;        A(A&&a):a_(std::move(a.getValue())){}        A& operator = (A&&) {}        explicit A(int a):a_(a){}        int getValue(){return a_;}    private:        int a_;};int main(){    std::vector< A > myVec;    myVec.reserve(10);    for(int i=0;i<10;++i)    {        A a(i);        myVec.push_back(std::move(a));//std::move    }    for(int i=0;i<10;++i)    {        std::cout<<myVec[i].getValue()<<std::endl;    }    return 0;}

代码中对于move constructor的声明定义如果去掉,将出现编译问题

参考:
https://stackoverflow.com/questions/26906014/non-copyable-elements-in-vector