在给函数使用原始变量时,更好的做法是什么:
unsigned long x = 4;
void func1(unsigned long& val) {
val = 5;
}
func1(x);
or:
void func2(unsigned long* val) {
*val = 5;
}
func2(&x);
勒夫:有什么理由选择一个而不是另一个吗?
在给函数使用原始变量时,更好的做法是什么:
unsigned long x = 4;
void func1(unsigned long& val) {
val = 5;
}
func1(x);
or:
void func2(unsigned long* val) {
*val = 5;
}
func2(&x);
勒夫:有什么理由选择一个而不是另一个吗?
当前回答
我真的认为你将受益于建立以下函数调用编码指南:
As in all other places, always be const-correct. Note: This means, among other things, that only out-values (see item 3) and values passed by value (see item 4) can lack the const specifier. Only pass a value by pointer if the value 0/NULL is a valid input in the current context. Rationale 1: As a caller, you see that whatever you pass in must be in a usable state. Rationale 2: As called, you know that whatever comes in is in a usable state. Hence, no NULL-check or error handling needs to be done for that value. Rationale 3: Rationales 1 and 2 will be compiler enforced. Always catch errors at compile time if you can. If a function argument is an out-value, then pass it by reference. Rationale: We don't want to break item 2... Choose "pass by value" over "pass by const reference" only if the value is a POD (Plain old Datastructure) or small enough (memory-wise) or in other ways cheap enough (time-wise) to copy. Rationale: Avoid unnecessary copies. Note: small enough and cheap enough are not absolute measurables.
其他回答
如果你要修改变量的值,你应该传递一个指针。 尽管在技术上传递引用或指针是相同的,但在用例中传递指针更具有可读性,因为它“通告”了函数将更改值的事实。
我的经验法则是:
如果你想对指针进行算术运算(例如,增加指针地址以遍历数组),或者如果你必须传递一个空指针,请使用指针。
否则使用引用。
引用类似于指针,除了不需要使用前缀*来访问引用所引用的值。同样,在初始化对象之后,不能引用另一个对象。
引用对于指定函数参数特别有用。
有关更多信息,请参阅“Bjarne Stroustrup”(2014)的“c++之旅”(A Tour of c++)第11-12页
指针:
可以被分配为nullptr(或NULL)。 在调用站点,如果你的类型本身不是指针,你必须使用&, 显式地修改对象。 指针可以被反弹。
引用:
不能为空。 一旦被束缚,就无法改变。 调用者不需要显式地使用&。有时这被认为是 不好,因为你必须去函数的实现看看 完成参数的修改。
我真的认为你将受益于建立以下函数调用编码指南:
As in all other places, always be const-correct. Note: This means, among other things, that only out-values (see item 3) and values passed by value (see item 4) can lack the const specifier. Only pass a value by pointer if the value 0/NULL is a valid input in the current context. Rationale 1: As a caller, you see that whatever you pass in must be in a usable state. Rationale 2: As called, you know that whatever comes in is in a usable state. Hence, no NULL-check or error handling needs to be done for that value. Rationale 3: Rationales 1 and 2 will be compiler enforced. Always catch errors at compile time if you can. If a function argument is an out-value, then pass it by reference. Rationale: We don't want to break item 2... Choose "pass by value" over "pass by const reference" only if the value is a POD (Plain old Datastructure) or small enough (memory-wise) or in other ways cheap enough (time-wise) to copy. Rationale: Avoid unnecessary copies. Note: small enough and cheap enough are not absolute measurables.