这篇博文介绍右值的概念。看一下下边的代码
void printInt(int& i){cout<<"lvalue reference: "<<i<<endl;}
void printInt(int&& i){cout<<"rvalue reference: "<<i<<endl;}
int main(){
//What is rvalue reference?
int a = 5; // a is a lvalue
printInt(a); //Call printInt(int& i)
pirntInt(6); //Call PrintInt(int&& i)
}
上面代码第8行就是右值引用的例子。下边的代码进一步讲解的这个概念。
#include <iostream>
using namespace std;
class boVector {
int size;
double* arr_;
public:
boVector(const boVector& rhs) { // Copy constructor
size = rhs.size;
arr_ = new double[size];
for (int i = 0; i < size; i++) { arr_[i] = rhs.arr_[i]; }
cout << "copy constructor " << endl;
}
boVector(boVector&& rhs) { // Move constructor
size = rhs.size;
arr_ = rhs.arr_;
rhs.arr_ = nullptr;
cout << "move constructor " << endl;
}
boVector() = default;
~boVector() { delete arr_; }
};
void foo(boVector v)
{
cout << "foo " << endl;
}
void foo_ref(boVector &v)
{
cout << "foo_ref " << endl;
}
boVector createBoVector() {//Creates a boVector
return boVector();
}
int main() {
boVector reusable = createBoVector();
foo(reusable); //是个左值,调用copy construct
foo(createBoVector()); //不调用任何constrcut
foo(std::move(reusable)); //是个右值,调用deep construct
boVector reusable1 = createBoVector();
foo_ref(reusable); //引用,不调用构造函数
return 0;
}
最后的话:
这篇文章发布在CSDN/蓝色的杯子, 没事多留言,让我们一起爱智求真吧.我的邮箱wisdomfriend@126.com