移动语义
C++11中引入了移动语义,目的是防止不必要的复制,以提高程序性能。若一个函数要返回临时对象,如果是自己创造的一个临时对象,那首先回调用该临时对象的构造函数,拷贝构造函数和析构函数。
RVO(return Value Optimization)是一种编译器的优化机制,它的目的就是为了消除为保存返回值而创建的临时对象。
右值引用:右值是一个生命周期短暂的值,比如函数体中的临时变量、常量等。通过右值引用可以延长右值的生命周期,其生命周期变成绑定该右值的变量的生命周期。
移动语义就是通过右值引用实现的。通过对类对象的移动构造函数,就可以完成了资源的转移,避免了对象成员的深拷贝操作,提高了代码的效率。
例子
#include <iostream>
#include <vector>
using namespace std;
class person {
private:
int age = 0;
string name = "";
public:
person() : age(-1), name("X") {
cout << "默认构造" << endl;
}
person(int a) : age(a), name(""){
cout << "列表初始化构造" << endl;
}
person(int a, string n) : age(a), name(n) {
cout << "列表初始化构造" << endl;
}
person(const person& a_person) {
cout << "拷贝构造函数" << endl;
this->age = a_person.age;
this->name = a_person.name;
}
person(person && a_person) {
cout << "移动构造函数" << endl;
this->age = a_person.age;
this->name = a_person.name;
}
person& operator=(const person& a_person) {
if (this == &a_person) {
return *this;
}
cout << "赋值运算符重载" << endl;
this->age = a_person.age;
this->name = a_person.name;
return *this;
}
~person() {
cout << "析构函数" << endl;
}
};
person getOBJ() {
person p(2, "bob");
return p;
}
int main() {
//person p2 = getOBJ();
vector<person> v;
//person p(1,"like");
v.emplace_back(1,"like"); //原地构造,也可以不原地构造
//v.push_back(person(2, "bob")); //不能原地构造
//cout << a << ", " << b << endl;
//cout << &a << ", " << &b << endl;
return 0;
}
std::move
std::move函数是将一个左值对象变换成一个右值对象。这样即使是一个左值,也能借助移动语义来完成资源的转移。
【注意】move并没有移动资源,它仅仅是将一个左值强制转换成右值。