【C++】对象优化

关于对象优化在我们开发的高效率的代码,有非常重要的作用。


首先我们学习对象使用的过程中背后调用了那些方法

现在我们有如下的测试类。

#include <iostream>
using namespace std;
class Test
{
public:
	Test(int a = 5, int b = 5) :ma(a), mb(b)
	{
		cout << "Test()" << endl;
	}
	~Test()
	{
		cout << "~Test()" << endl;
	}
	Test(const Test&src):ma(src.ma),mb(src.mb)
	{
		cout << "Test(const Test&src)" << endl;
	}
	void operator=(const Test&src)
	{
		ma = src.ma;
		mb = src.mb;
		cout << "operator=" << endl;
	}
private:
	int ma;
	int mb;
};

现在我们有如下代码测试

Test t1(10, 10); // 1.Test(int, int)
int main()
{
	Test t2(20, 20); // 3.Test(int, int)
	Test t3 = t2; // 4.Test(const Test&)
	// static Test t4(30, 30);
	static Test t4 = Test(30, 30); // 5.Test(int, int)
	t2 = Test(40, 40); // 6.Test(int, int) operator= ~Test()
	// (50, 50) =  (Test)50; Test(int)
	t2 = (Test)(50, 50); // 7.Test(int,int) operator=  ~Test()
	t2 = 60; //Test(int) 8.Test(int,int) operator= ~Test()
	Test *p1 = new Test(70, 70); // 9. Test(int,int) 
	Test *p2 = new Test[2]; // 10. Test(int,int) Test(int,int)
	Test *p3 = &Test(80, 80); // 11. Test(int,int)  ~Test()
	const Test &p4 = Test(90, 90); // 12. Test(int,int)
	delete p1; // 13.~Test()
	delete[]p2; // 14. ~Test() ~Test()
}
Test t5(100, 100); // 2.Test(int, int)

运行结果:

这里需要注意的是,

1,static静态变量在main开始之前就有了内存空间,但是直到第一次执行到static的时候才对它进行初始化。

2,const Test &p4 = Test(90, 90); // 12. Test(int,int)这里定义了常引用引用了一个临时对象,使得临时对象的生存期变长。直到main函数结束才执行这个被引用临时对象的析构函数

3,t2 = (Test)(50, 50); // 7.Test(int,int) operator=  ~Test()    这里使用括号里面的右边的50为临时对象的构造函数的参数。


我们再看如下的代码

#include <iostream>
using namespace std;
class Test
{
public:
	Test(int data = 10) :ma(data)
	{
		cout << "Test(int)" << endl;
	}
	~Test()
	{
		cout << "~Test()" << endl;
	}
	Test(const Test &t) :ma(t.ma)
	{
		cout << "Test(const Test &)"<<endl;
	}
	void operator=(const Test &t)
	{
		cout << "operator=" << endl;
		ma = t.ma;
	}
	int getData()const {
		return ma;
	}
private:
	int ma;
};
Test GetObject(Test t)
{
	int val = t.getData();
	Test tmp(val);
	return tmp;
}
int main()
{
	Test t1;
	Test t2;
	t2 = GetObject(t1);
	return 0;
}

测试结果:

main函数中的操作共有11个生成对象的函数被调用。

优化1

Test GetObject(Test &t)
{
	int val = t.getData();
	Test tmp(val);
	return tmp;
}

将函数的参数改为引用,参数使用引用传递使得函数减少到9

优化2

将函数的返回对象按照临时对象返回

Test GetObject(Test &t)
{
	int val = t.getData();
	//Test tmp(val);
	return Test(val);
}

结果:

函数调用减少到了7

优化3

构造对象t2的时候使用拷贝构造

int main()
{
	Test t1;
	Test t2 = GetObject(t1);
	//t2 = GetObject(t1);
	return 0;
}

结果:(函数的调用减少到了4个)

 

从上面优化的过程中总结:

1. 函数参数传递过程中,对象优先按引用传递,不要按值传递
2. 函数返回对象的时候,应该优先返回一个临时对象,而不要返回一个定义过的对象
3. 接收返回值是对象的函数调用的时候,优先按初始化的方式接收,不要按赋值的方式接收

 

懂得对象优化对于开发的效率有极大的提升。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值