关于返回临时对象的优化

看书遇到了临时对象,这里先说一下临时对象的返回值优化,下一篇会说临时对象的常量引用和非常量引用的问题。

在类中,重载operator*,返回一个新的类对象,会生成一个新的对象,会带来不必要的开销,如何降低呢?

#include <iostream>
using namespace std;
class Test
{
public:
	Test(int x, int y)
		:_x(x), _y(y) 
	{
		cout << "Test(int x,int y) called" << endl;
	}
	Test()
	{ 
		cout << "Test() called" << endl;
	}
	Test(const Test & another)
	{
		this->_x = another._x;
		this->_y = another._y;
		cout << "Test (const Test& another) called" << endl;
	}
	Test operator=(const Test& another)
	{
		cout << "Test operator=() called" << endl;
	}
	inline Test operator*(const Test& another)
	{
		return Test(this->_x*another._x, this->_y*another._y);//返回临时对象

		//Test result(this->_x*another._x, this->_y*another._y);//创建局部变量并返回
		//return result;
	}
private:
	int _x;
	int _y;
};


int main()
{ 
	Test a(1, 3);
	Test b(2, 5);
	Test c = a * b;
 	getchar();
 	return 0;
}

推测结果,调用三次构造函数,一次拷贝构造函数。

但是事实是,只调用了三次构造函数。

观察operator*返回部分的表达式

return Test(this->_x*another._x, this->_y*another._y);

通过这个表达式建立了一个临时对象,返回Test而不出现局部对象,这样已经减少了开销,C++规则允许编译器优化不出现的临时对象,所以编译器就会被允许消除在operator*建立的临时对象和返回的临时对象,,这样调用operator*的临时对象的开销就是0,此处通过inline的方式又消除了调用开销。

如果通过返回局部变量的方式会增大开销,调用三次构造函数,一次拷贝构造函数。

猜你喜欢

转载自blog.csdn.net/znzxc/article/details/81167628