先看两个源文件
1.
- #include <stdio.h>
-
#include <string>
-
using namespace std;
-
class person
-
{
-
public:
-
person()
-
{
-
;
-
}
-
~person()
-
{
-
;
-
}
-
virtual void eat()
-
{
-
printf("I am a person to eat\n");
-
}
-
private:
-
std::string name;
-
std::string address;
-
};
-
class student : public person
-
{
-
public:
-
student()
-
{
-
;
-
}
-
~student()
-
{
-
;
-
}
-
virtual void eat()
-
{
-
printf("I am a student to eat\n");
-
}
-
private:
-
std::string schoolname;
-
std::string schoolAddress;
-
};
-
void test(student x)
-
{
-
x.eat();
-
}
-
/*
-
void test(student& x)
-
{
-
x.eat();
-
}*/
-
int main()
-
{
-
student x1;
-
for(int i = 0 ;i<10;i++)
-
{
-
test(x1);
-
}
-
return 0;
-
}
2.
- #include <stdio.h>
-
#include <string>
-
using namespace std;
-
class person
-
{
-
public:
-
person()
-
{
-
;
-
}
-
~person()
-
{
-
;
-
}
-
virtual void eat()
-
{
-
printf("I am a person to eat\n");
-
}
-
private:
-
std::string name;
-
std::string address;
-
};
-
class student : public person
-
{
-
public:
-
student()
-
{
-
;
-
}
-
~student()
-
{
-
;
-
}
-
virtual void eat()
-
{
-
printf("I am a student to eat\n");
-
}
-
private:
-
std::string schoolname;
-
std::string schoolAddress;
-
};
-
/*
-
void test(student x)
-
{
-
x.eat();
-
}*/
-
-
void test(student& x)
-
{
-
x.eat();
-
}
-
-
int main()
-
{
-
student x1;
-
for(int i = 0 ;i<10;i++)
-
{
-
test(x1);
-
}
-
return 0;
-
}
现在对这两个函数分别运行,进行计时,最后我们会惊奇的发现一个有趣的现象:
第一个程序的运行结果:
nick@nick-VirtualBox:~/Public/C++testpoj$ time ./a.out
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
real 0m0.023s
user 0m0.000s
sys 0m0.000s
第二个程序的运行结果:
nick@nick-VirtualBox:~/Public/C++testpoj$ time ./a.out
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
I am a student to eat
real 0m0.003s
user 0m0.004s
sys 0m0.000s
大家有没有发现,real的时间参数第二段代码的运行速度明显要比第一段的要快,这是为什么呢?
接下来我们就探寻一下!!!!!!!!!!!!!!
这两端程序唯一的不同点就在于:
- void test(student x)
-
{
-
x.eat();
-
}
-
-
void test(student& x)
-
{
-
x.eat();
-
}
这两个函数传递的参数不同,第一段代码是值传递,第二段是传递的对象引用
那为什么用引用的程序运行速度会比值传递的程序运行的快那么多呢?
我们先看下第一个程序,main函数中,通过值传递参数的方法,本质上,会对传送的对象进行一次拷贝,即调用拷贝构造函数,然后当函数执行完,便要对这个对象进行析构,那又需要调用一次析构函数,然后,这只是一个开始,应为student对象是继承person对象,所以,在构造student对象前还要调用父类的拷贝构造函数,哪当然也要调用一次析构函数。我们还注意到两个类中的成员变量,在创建时也要调用构造析构函数,这样算一算,当传递一次值参的时候,系统偷偷的已经执行了6次拷贝构造,析构操作。
而第二个程序通过引用传递的参数,则没有复制参数这个操作,我想有点c++基础的朋友都能想明白这个道理这里我就不讲了。
从这点看,果然值传递的效率比引用传递慢了许多了!!!!!!
然而引用还有比值传递更优越的地方,下次我们继续讨论这点
阅读(1557) | 评论(0) | 转发(0) |