c++11 右值引用 && std::move()

在学习c++的线程标准库的时候同时碰到了右值引用(&&)和c++11的move构造函数,

简单的看了几篇博客,大概了解了左值、左值引用、右值、右值引用以及在左值明确放弃对其资源的所有权,通过std::move()来将其转为右值引用这五点内容:

 

以下链接都很简短,看两遍我相信就能有比较好的理解了:

浅析C++11右值引用和move语义

左值、左值引用、右值、右值引用

c++为什么用右值引用

 

一个std::move()的例程(参考:c++11 std::move() 的使用

#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 << ""
";
    //调用移动构造函数,掏空str,掏空后,最好不要使用str
    v.push_back(std::move(str));
    std::cout << "After move, str is "" << str << ""
";
    std::cout << "The contents of the vector are "" << v[0]
                                         << "", "" << v[1] << ""
";
}

可以看到,std::move()就是将左值转换为对应的右值引用类型,且调用后销毁

原文地址:https://www.cnblogs.com/exciting/p/11156900.html