40.move()

版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/83118909

右值引用只能绑定到临时对象:

1)所引用的对象将会被销毁。当我们对一个左值用move转换为右值引用之后,这个左值就像是被掏空了,只能够被赋值或者销毁,不能做其他的操作!

2)该对象没有其他的用户共享。

std::move 可以以非常简单的方式将左值引用转换为右值引用。

std::move本质上是提高性能,减少不必要的拷贝操作,能移动就不拷贝!

std::move 将一个对象的状态或者所有权转移到另外一个对象上。

打个比方,你有5块钱,你弟没有钱,你弟想找你妈妈要5块钱。你妈妈不打算给,因为这样又没了5块(消耗大)。你妈于是直接将你的5块给了你弟。此时,你就没有钱了。你弟有钱。就是这个道理。



#include <iostream>

#include <utility>

#include <vector>

#include <string>

int main()

{

    std::string str = "Hello";

    std::vector<std::string> v;

    //调用常规的拷贝构造函数,新建字符数组,拷贝数据

    v.push_back(str);

    std::cout << "After copy, str is \"" << str << "\"\n";

    //调用移动构造函数,掏空str,掏空后,最好不要使用str

    v.push_back(std::move(str));

    std::cout << "After move, str is \"" << str << "\"\n";

    std::cout << "The contents of the vector are \"" << v[0]

                                         << "\", \"" << v[1] << "\"\n";
    system("pause");
    return 0;

}

输出:

After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"

猜你喜欢

转载自blog.csdn.net/Fly_as_tadpole/article/details/83118909
40