第27月第11天 右值引用

1.

 

拷贝的开销可以很大。举例来说,对于std::vector,像v2=v1这样的赋值通常包含一次函数调用,一次内存分配和一个循环。当我们确实需要一个vector的两份拷贝时,这当然是可接受的,然而很多情况下我们并不需要:我们常常将一个vector从一个地方复制到另一个地方,接着便覆写了旧的版本。考虑下面的代码:

 

https://blog.csdn.net/steedhorse/article/details/6847937

 

class A
{
private:
    int data;
public:
    A(int i):data(i) { std::cout << "调用构造函数" << std::endl; }
    A(const A& other) {
        std::cout << "调用拷贝构造函数" << std::endl;
        data = other.data;
    }
    A& operator=(const A& other) {
        std::cout << "使用赋值运算符" << std::endl;
        data = other.data;
     return *this; }
~A() { std::cout << "调用析构函数" << std::endl; } }; int main() { A a(1); A b(2); vector<A> v1; v1.push_back(a); v1.push_back(b); vector<A> v2(boost::move(v1)); return 0; }

 

posted @ 2018-12-11 10:56  lianhuaren  阅读(92)  评论(0编辑  收藏  举报