4

c++传入参数的问题

 3 years ago
source link: https://www.ascotbe.com/2018/12/08/C++TheProblemOfIncomingParameters/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
c++传入参数的问题 | ascotbe
int tex (int a,int b)

值传递:有一个形参向函数所属的栈拷贝数据的过程,如果值传递的对象是类对象或是大的结构体对象,将耗费一定的时间和空间。

int tex(int *a,int *b)

指针传递:同样有一个形参向函数所属的栈拷贝数据的过程,但拷贝的数据是一个固定为4字节的地址。

int tex(int &a,int &b)

引用传递:同样有上述的数据拷贝过程,但其是针对地址的,相当于为该数据所在的地址起了一个别名。

效率上讲,指针传递和引用传递比值传递效率高。一般主张使用引用传递,代码逻辑上更加紧凑、清晰。

引用传递做函数参数”是C++的特性,C语言不支持。

如果是值的传递,是拷贝过去的就是在用的函数中修改了那个值也不会影响到原先的值
若果是引用的传递,虽然是数据拷贝但是在用的函数中修改了那个值是会影响到原先的值


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK