c++ 临时对象的来源临时对象的来源
大家可能对这个临时对象这个概念还不是很清楚,那么首先我们花一些时间来理解临时对象
首先看下面一端代码:
复制代码 代码如下:
#include <iostream>
void swap( int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
int main(int argc,char** argv)
{
int a=1,b=2;
swap(a,b);
std::cout<<a<<"-----"<<b<<std::endl;
return 0;
}
结果为
2-----1
可能大多数园友,认为"int temp"是"临时对象",但是其实不然,"int temp"仅仅是swap函数的局部变量。
临时对象是代码中看不到的,但是实际程序中确实存在的对象。临时对象是可以被编译器感知的。
为什么研究临时对象?
主要是为了提高程序的性能以及效率,因为临时对象的构造与析构对系统开销也是不小的,所以我们应该去了解它们,知道它
们如何造成,从而尽可能去避免它们。
临时对象建立一个没有命名的非堆对象会产生临时对象。(不了解什么是堆对象和非堆对象,可以参考C++你最好不要做的这
一博文,这里面有介绍。)这种未命名的对象通常在三种条件下产生:为了使函数成功调用而进行隐式类型转换时候、传递函
数参数和函数返回对象时候。
那么首先看看为了使函数成功调用而进行隐式类型转换。
复制代码 代码如下:
#include <iostream>
int countChar(const std::string & s,const char c)
{
int count=0;
for(int i=0;i<s.length( );i++)
{
if(*(s.c_str( )+i) == c)
{
count++;
}
}
return count;
}
int main(int argc,char** argv)
{
char buffer[200];
char c;
std::cout<<"please input the string:";
std::cin>>buffer;
std::cout<<"please input the char which you want to chount:";
std::cin>>c;
int count=countChar(buffer,c);
std::count<<"the count is:"<<count<<std::endl;