C++返回值优化

本文探讨了C++中函数返回对象的两种常见方式:直接返回对象和预先构造对象再返回。通过示例代码,解释了编译器如何对返回值进行优化,特别是在方式1中,编译器会直接将对象构造在返回值的内存位置,避免了拷贝构造和析构的过程,从而提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当函数需要返回对象时,通常有两种写法,一种是直接在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上进行,从而减少拷贝构造函数的调用次数和产生对象的个数


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值