当函数需要返回对象时,通常有两种写法,一种是直接在return语句中返回一个对象,一种是先构造好一个对象,然后在return中将其返回。以下代码为例:
#include <iostream>
#include <string>
using namespace std;
struct Node{
string name;
int x, y;
Node(string na = "", int xx = 0, int yy = 0) : name(na), x(xx), y(yy) {
cout << name << " " << "constructed" << endl;
cout << "address " << this << endl;
}
Node(const Node& n) : name(n.name), x(n.x), y(n.y) {}
~Node() {cout << name << " " << "deconstructed" << endl; }
};
Node add_1(const Node& a, const Node& b){
return Node(string("temp object"), a.x + b.x, a.y + b.y);
}
Node add_2(const Node& a, const Node& b){
Node local(string("local object"), a.x + b.x, a.y + b.y);
return local;
}
int main(){
Node n1(string("n1"), 1, 1);
Node n2(string("n2"), 2, 2);
Node res_1 = add_1(n1, n2);
cout << "res_1's address is " << &res_1 << endl;
cout << "--------add_1 returned---------" << endl;
Node res_2 = add_2(n1, n2);
cout << "--------add_2 returned---------" << endl;
cout << "res_2's address is " << &res_2 << endl;
return 0;
}
编译器对add_1和add_2返回值的处理方式不一样,对方式1,临时对象作返回值,编译器明白对这个临时对象没有其他需求,只是返回它,因此编译器直接把这个对象创建在外部返回值的内存单元,因为不是真正创建一个局部对象,所以仅需要一个普通的构造函数调用(不需要拷贝构造函数),且不会调用析构函数,效率很高。
而对方式2, 首先创建temp对象,调用构造函数,然后拷贝构造函数把temp拷贝到外部返回值的存储单元里,最后,当temp在作用域的结尾时调用析构函数。( 但是,实际中不同编译器对此的处理方式不同,GCC4.8.1对这种方式的处理跟方式1一样,都不调用拷贝构造函数,而MS的编译器则如上所述。而这种优化方式,其实就是NRV优化,Named
Return Value,有名字的返回变量优化,内部将返回值_result作为参数传进函数,对返回变量的操作实际都在这个_result上进行,从而减少拷贝构造函数的调用次数和产生对象的个数)。