C++深度解析 临时对象 --- 直接调用构造函数,手动去调用构造函数(22)
临时对象(直接调用构造函数。代码上手动去调用而非编译器自己调用构造函数)
直接调用构造函数将产生一个临时对象。
临时对象的生命周期只有一条语句的时间。
临时对象的作用域只在一条语句中。
临时对象是C++中值得警惕的灰色地带。
示例程序:(临时对象的引入,在构造函数中调用构造函数)
#include <stdio.h>
class Test
{
int mi;
public:
Test(int i)
{
mi = i;
}
//在构造函数中调用构造函数
Test()
{
//得到一个临时对象,只在这条语句有效,临时对象没有名字
//这个构造函数 等价为 空
Test(0);
}
void print()
{
printf("mi = %d\n", mi);
}
};
int main()
{
Test t;
t.print();
return 0;
}
结果如下:
分析:
上述代码程序意图:(想代码的复用)
- 在Test()中以0作为参数调用Test(int i)
- 将成员变量mi的初始值设置为0
运行结果:
- 成员变量mi的值为随机值,这就是临时对象捣的鬼。
现代C++编译器在不影响最终执行结果的前提下,会尽力减少临时对象的产生!!!
示例程序一:
#include <stdio.h>
class Test
{
int mi;
public:
Test(int i)
{
printf("Test(int i):%d\n", i);
mi = i;
}
Test(const Test& t)
{
printf("Test(const Test& t):%d\n", t.mi);
mi = t.mi;
}
Test()
{
printf("Test()\n");
mi = 0;
}
int print()
{
printf("mi = %d\n", mi);
}
~Test()
{
printf("~Test()\n");
}
};
Test func()
{
return Test(20);
}
int main()
{
//现代C++编译器在不影响最终执行结果的前提下,会尽力减少临时对象的产生!!!
Test t = Test(10); //等价 Test t = 10;(编译器优化后)
Test tt = func(); //等价 Test tt = Test(20); ==> Test tt = 20;(编译器优化后)
t.print();
tt.print();
return 0;
}
分析:程序中,Test(10)很明显会产生一个临时对象,并将该临时对象赋值给对象t。这里的赋值操作自然会调用到拷贝构造函数,所以猜测程序的运行结果为:
Test(int i) //Test(10)所致
Test(const cls& m) // = 所致
~Test() //临时对象销毁所致
~Test() //t对象销毁所致
结果如下:
分析:若依上面我猜测的程序执行流程运行程序,可见t对象产生需要经过两个构造函数:带参构造函数(临时对象调用)和拷贝构造函数(赋值类对象用),比起构造函数一次调用,显然效率低下得多,特别是在构造函数需要实现较多逻辑功能的时候。所以编译器做了优化,摈弃了临时对象的产生。优化后的代码应为:
Test t = Test(10); //源代码
Test t = 10; //编译器优化后
回到刚开始的程序:
Test()
{
//得到一个临时对象,只在这条语句有效,临时对象没有名字
//这个构造函数 等价为 空
Test(0);
}
事实上,Test(0)会生成一个临死对象,而0是初始化这个临时对象的。该行代码执行过后,临时对象便会销毁,所以不能实现程序预先的目的。
示例程序二:(将上面的程序进行优化,人为避开临时对象,对比上面的程序)
#include <stdio.h>
class Test
{
int mi;
public:
Test(int i)
{
printf("Test(int i):%d\n", i);
mi = i;
}
Test(const Test& t)
{
printf("Test(const Test& t):%d\n", t.mi);
mi = t.mi;
}
Test()
{
printf("Test()\n");
mi = 0;
}
int print()
{
printf("mi = %d\n", mi);
}
~Test()
{
printf("~Test()\n");
}
};
int main()
{
//现代C++编译器在不影响最终执行结果的前提下,会尽力减少临时对象的产生!!!
Test t = 10; //等价 Test t = 10;
Test tt = 20; //等价 Test tt = Test(20); ==> Test tt = 20;
t.print();
tt.print();
return 0;
}
小结
直接调用构造函数将产生一个临时对象
临时对象是性能的瓶颈,也是bug的来源之一
现代C++编译器会尽力避开临时对象
实际工程开发中需要人为的避开临时对象