以下内容参考https://blog.csdn.net/china_jeffery/article/details/78520237
右值引用若不作为函数参数使用,基本等于滥用
右值引用 (Rvalue Referene) 是 C++ 新标准 中引入的新特性 , 它实现了移动语义 (Move Sementics) 和完美转发 (Perfect Forwarding)。它的主要目的有两个方面:
1. 消除两个对象交互时不必要的对象拷贝,节省运算存储资源,提高效率。
2. 能够更简洁明确地定义泛型函数。
何为右值:
C++( 包括 C) 中所有的表达式和变量要么是左值,要么是右值。通俗的左值的定义就是非临时对象,
那些可以在多条语句中使用的对象。 所有的变量都满足这个定义,在多条代码中都可以使用,都是左值。
右值是指临时的对象,它们只在当前的语句中有效。
int i = 0;// 在这条语句中,i 是左值,0 是临时变量,就是右值
在C++11之前,右值是不能引的,如
int &a = 1;// error : 非常量的引用必须为左值 const int &a = 1;// 我们最多只能用常量引用来绑定一个右值
在C++11中我们可以引用右值,使用&&实现:
int &&a = 1;
应用场景:
如下string类,实现了拷贝构造和赋值运算符重载
#include <iostream> #include <vector> using namespace std; class MyString { public: MyString() { m_data = NULL; m_len = 0; } MyString(const char* s) { m_len = strlen(s); init_data(s); cout << "构造函数" << s << endl; } MyString(const MyString& str) { m_len = str.m_len; init_data(str.m_data); cout << "拷贝构造函数" << str.m_data << endl; } MyString& operator=(const MyString& str) { if ( this != &str ){ this->m_len = str.m_len; init_data(str.m_data); } cout << "等号操作符重载" << str.m_data << endl; return *this; } ~MyString() { if ( m_data != NULL ){ cout << "析构函数" << endl; free(m_data); } } private: void init_data(const char* s) { m_data = new char[m_len + 1]; memcpy(m_data, s, m_len); m_data[m_len] = '