本文参照于狄泰软件学院,唐佐林老师的——《C++深度剖析教程》
C++中有这样一种对象:它在代码中看不到,但是确实存在。它就是临时对象!
临时对象是由编译器定义的一个没有命名的非堆对象。
为什么研究临时对象?
主要是为了提高程序的性能以及效率,因为临时对象的构造与析构对系统性能而言绝不是微小的影响,所以我们应该去了解它们,知道它们如何造成,从而尽可能去避免它们。
因为在项目中,一个类中所包含的成员变量和成员函数是很庞大的,因此对应的构造函数需要初始化大量的数据,耗费CPU的资源。如果程序中存在大量临时变量的生成就意味着会调用多次构造函数,影响程序的性能以及效率。
调用构造函数产生临时对象
示例代码:有趣的问题
#include <stdio.h>
#include <iostream>
using namespace std;
class Test
{
int mi;
public:
Test(int i)
{
cout << "Test(int i)" << endl;
mi = i;
}
Test()
{
cout << "Test()" << endl;
Test(0);
}
void print()
{
printf("mi = %d\n", mi);
}
~Test()
{
cout << "~Test()" << endl;
}
};
int main()
{
Test t;
t.print();
return 0;
}
程序意图:
1. 在Test() 中以0作为参数调用 Test(int i)
2. 将成员变量mi的初始值设置为0
输出结果:
Test()
Test(int i)
~Test()
mi = 49
~Test()
看到这个输出,我们有几个疑问?
1. 成员变量mi的值为随机值,究竟哪个地方出了问题?
2. 构造函数是否可以直接调用?直接调用构造函数的行为是什么?
3. 是否可以在构造函数中调用构造函数?
4. 直接调用构造函数的行为是什么?
分析:
1. 输出两次析构函数,意味着产生了两个对象。
输出结果说明了直接调用构造函数会产生一个不知名的临时对象。
2. 直接调用构造函数,会产生一个临时对象,临时对象的生命周期只有一句语句的时间。
生命周期为一条语句,这就说明了临时对象的作用域也只有一句。编译器也会自动销毁这个临时对象,所以没有为mi初始化成功。
3. 临时对象是C++中值得警惕的灰色地带
防止产生临时对象的方法
问题:如何解决直接调用构造函数产生的临时对象?
不要直接调用构造函数,编写一个初始化函数再进行调用。
#include <stdio.h>
#include <iostream>
using namespace std;
class Test
{
int mi;
void init(int i)
{
mi = i;
}
public:
Test()
{
cout << "Test()" << endl;
init(0);
}
void print()
{
printf("mi = %d\n", mi);
}
~Test()
{
cout << "~Test()" << endl;
}
};
int main()
{
Test t;
t.print();
return 0;
}
通过函数传递对象产生的临时对象
还有什么情况可能产生临时对象呢?函数传递对象。
示例代码:通过函数传递对象
#include <stdio.h>
#include <iostream>
using namespace std;
class People
{
public:
People(const char* n, int a) : name(n), age(a)
{
cout << "People(const char* n, int a) : name(n), age(a)" << endl;
}
People()
{
cout << "People()" << endl;
}
People(const People& P)
{
name = P.name;
age = P.age;
cout << "People(const People& P)" << endl;
}
~People()
{
cout << "~People()" << endl;
}
private:
const char *name;
int age;
};
void swap(People p1, People p2)
{
printf("temporary constructor\n");
}
int main(int argc, char *argv[])
{
People p1("oushangrong", 18);
People p2("Shaw", 20);
swap(p1,p2);
cout << "swap(p1, p2)" << endl;
return 0;
}
输出结果:
People(const char* n, int a) : name(n), age(a)
People(const char* n, int a) : name(n), age(a)
People(const People& P)
People(const People& P)
temporary constructor
~People()
~People()
swap(p1, p2)
~People()
~People()
分析:
1. 根据函数调用的过程其实我们也可以知道,实际上实参会拷贝一份给函数形参。所以会调用拷贝构造函数。
- 拷贝构造函数也只有一句语句的生命周期。
使用引用解决函数参数产生的临时对象
问题:如何解决函数参数传递产生临时对象的这个问题?
我们可以使用引用实参来达到目的
void swap(People &p1, People &p2)
{
printf("temporary constructor\n");
}