在C++11中,编译器有可能在某些情况下(比如对临时对象的优化)使用移动构造函数来优化代码的性能。但它不会使用移动构造函数来移动一个命名的变量,因为这个变量的名字可以在程序的其它地方被使用。
以下代码演示了这个问题:
#include
using namespace std;
class A {
public:
A() { cout << "Default constructor called." << endl; } // 默认构造函数
A(const A& obj) { cout << "Copy constructor called." << endl; } // 拷贝构造函数
A(A&& obj) { cout << "Move constructor called." << endl; } // 移动构造函数
};
A GetObject() {
A obj;
return obj;
}
int main() {
A a = GetObject();
return 0;
}
输出结果为:“Default constructor called.”“Move constructor called.”。说明编译器在使用GetObject函数返回临时对象时,会通过移动构造函数来避免不必要的拷贝,从而提高代码的性能。
下一篇:编译器会自动取消函数的内联吗?