关于对象优化在我们开发的高效率的代码,有非常重要的作用。
首先我们学习对象使用的过程中背后调用了那些方法
现在我们有如下的测试类。
#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. 接收返回值是对象的函数调用的时候,优先按初始化的方式接收,不要按赋值的方式接收