好久木有写博客了,前一段时间忙着毕业论文和答辩。最近对游戏开发方面比较有兴趣,就学习了一下C++,因为很多游戏引擎都支持C++。花了几天的时间基本系统的学习了一下C++的语法规范,看得是范类的C++视频教程。这里附上网盘地址:http://pan.baidu.com/s/1c0lB1Pu ,废话不多说鸟,看下面
分别用代码表示一下三种返回:
A fn1(A a) //按值返回
A* fn3(A *a)//按址返回
A& fn2(A &a)//按别名返回
三个函数看起来产不多,但造成的开销是不同的。按址返回和按别名返回的开销是一样的,都比较小,按值返回的开销则比较大。因为这里演示的按值返回不管是传参或者返回时,都会调用类A的复制构造函数,创建一个类A的副本,将原对象的成员数据一个个拷贝到副本上,加入类A的成员数据很大的话,循环调用多几次这个函数造成的开销是不估量的,下面就用代码演示一下;
首先定义一个A类,
按值返回:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| #include <iostream> using namespace std;
class A { public: A(int j){ cout << "构造函数ggg" << endl; this->i = j; } A(A const &a){ cout << "复制构造函数fff" << endl; this->i = a.i; i++; } ~A(){ cout << "析构函数xxx" << endl; } int get(){ return this->i; } private: int i; }; A fn1(A a) { cout << a.get() << endl; return a; } void main() { A a(4); A b(4); cout << a.get() << endl; b = fn1(a); cout << b.get() << endl;
system("pause"); }
|
结果:

按址返回:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| A* fn3(A *a) { cout << a->get() << endl; return a; } void main() { A c(4); cout << c.get() << endl; A &d = fn2(c); cout << d.get() << endl;
system("pause"); }
|
结果:

按别名返回:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| A& fn2(A &a) { cout << a.get() << endl; return a; } void main() { A c(4); cout << c.get() << endl; A &d = fn2(c); cout << d.get() << endl;
system("pause"); }
|
结果:

从结果可以看出来按 址返回和按地址返回的开销是一样的