1、优化规则
函数参数传递优先使用传引用,而不是传值
①、函数参数传递的过程是赋值的过程,对象之间赋值是会产生赋值运算符的重载调用,退出函数时还会再调用一次析构函数,传引用就不存在上述函数调用
2、代码
#include<iostream>
using namespace std;
static int g_count = 1;
class test
{
public:
//构造函数
test(int p=10){ma = p ; cout<<g_count++<<" test(int)"<<endl;}
//析构函数
~test(){cout<<g_count++<<" ~test()"<<endl;}
//拷贝构造函数
test (const test &p)
{
ma = p.ma;
cout<<g_count++<<" operator(test)"<<endl;
}
//赋值运算符的重载
test& operator=(const test p)
{
ma = p.ma;
cout<<g_count++<<" operator = (test)"<<endl;
return *this;
}
public:
int getdata(){return ma;}
private:
int ma;
};
//test getobj(test t)
test getobj(test &t)
{
int val = t.getdata();
test tmp(val);
return tmp;
}
int main()
{
test t1;
test t2;
t2 = getobj(t1);
return 0;
}