c ++ * vs&在函数声明 [英] c++ * vs & in function declaration

查看:150
本文介绍了c ++ * vs&在函数声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C ++中的指针变量和引用变量之间的差异


什么时候应该声明我的变量作为指针vs对象传递的引用?它们在汇编中编译为同一个东西(至少是渐近的运行时),所以我什么时候应该使用它?

  void foo obj * param)
void foo(obj& param)


解决方案>

我的规则很简单:使用*当你想显示的值是可选的,因此可以是0.



排除规则:所有_obj_s周围存储在容器中,并且您不想通过使用无处不在的 foo(* value); 而不是 foo(value) ;
那么就要显示该值不能为0在函数begin处插入 assert(value); >

Possible Duplicate:
Difference between pointer variable and reference variable in C++

When should I declare my variables as pointers vs objects passed-by-reference? They compile to the same thing in assembly (at least run-time asymptotically) so when should I use which?

void foo(obj* param)
void foo(obj& param)

解决方案

My rule is simple: use * when you want to show that value is optional and thus can be 0.

Excluding from the rule: all the _obj_s around are stored in containers and you don't want to make your code look ugly by using everywhere foo(*value); instead of foo(value); So then to show that value can't be 0 put assert(value); at the function begin.

这篇关于c ++ * vs&在函数声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆