27 C++ 临时对象

学习临时对象的目的

了解临时对象产生的原因,改进代码让尽量产生临时产量,因为临时变量会消耗系统资源。

产生临时对象的3中情况以及解决方案。

第一种:以值的方式给函数传递参数

class Teacher75 {
public:
	Teacher75() {
		cout << "Teacher75 构造函数" << this<< endl;
	}
	Teacher75(const Teacher75 & t) {
		this->m_age = t.m_age;
		cout << "Teacher75 copy 构造函数" << this<< "   t = " << &t<m_age = t.m_age;
		return *this;
	}
	int m_age;
};

//第一种:以值的方式给函数传递参数,这里参数是 Teacher75,
//当实参传递给形参的时候,会调用copy 构造函数,将实参传递copy 给形参 
void getTeacher75age(Teacher75 t) {
	cout << t.m_age << endl;
}

//第一种解决方案:
void getTeacher75agefix(Teacher75& t) {
	cout << t.m_age << endl;
}
void main() {
	Teacher75 t1;
	t1.m_age = 28;
	//第一种:以值的方式给函数传递参数
	getTeacher75age(t1);

	cout << "-----" << endl;
	Teacher75 t2;
	t2 = t1;
	cout << "---使用引用的方式传递函数参数---" << endl;
	getTeacher75agefix(t1);
}

第二种,函数返回临时对象的时候

//第二种,函数返回临时对象的时候
class Teacher76 {
public:
	Teacher76() {
		cout << "Teacher76 构造函数" << this << endl;
	}
	Teacher76(int age):m_age(age) {
		cout << "Teacher76 构造函数" << this << endl;
	}
	Teacher76(const Teacher76 & t) {
		this->m_age = t.m_age;
		cout << "Teacher76 copy 构造函数" << this << "   t = " << &t << endl;
	}

	Teacher76& operator=(const Teacher76 & t) {
		cout << "Teacher76 operator =  函数" << this << endl;
		this->m_age = t.m_age;
		return *this;
	}
	~Teacher76() {
		cout << "Teacher76 析构函数" << this << endl;
	}
	int m_age;

};

//问题,实际上是多一次 copy 构造函数调用
Teacher76 getTeacher76(){
	Teacher76 temp; //Teacher76 构造函数000000A584D8F564
	temp.m_age = 87;
	return temp; //Teacher76 copy 构造函数000000A584D8F784   t = 000000A584D8F564
}

//解决方案,在可以的case下 直接return 
Teacher76 getTeacher76fix() {
	return Teacher76(87); 
}

void main() {
	getTeacher76();

	//  Teacher76 构造函数000000A584D8F564  temp 构造函数被调用
	//	Teacher76 copy 构造函数000000A584D8F784   t = 000000A584D8F564   return 时,会调用copy 构造函数
	//  多了一个构造函数
	//	Teacher76 析构函数000000A584D8F564  // temp 被析构
	//	Teacher76 析构函数000000A584D8F784 //返回的copy出来的这个构造函数,没有接,因此也析构

	cout << "断点在这里" << endl;

	getTeacher76fix();
	//  Teacher76 构造函数00000085234FFB94
	//	Teacher76 析构函数00000085234FFB94
}

第三种 隐式类型转换

//第三种 隐式类型转换
int count(const string& source,char ch) {
	return 8;
}
void main() {
	char charshuzu[100] = "abcc";
	int ncount = count(charshuzu,'a');
	//这里调用为了能调用成功, charshuzu会被从char [100],隐式转换成 const string 。

	//这会有隐式转换发生。

	//改法:不要让C++编译器帮忙转,自己转。
	string mystr = "mnv";
	int ncount222 = count(mystr, 'a');
}

你可能感兴趣的:(c++,开发语言)