在给函数使用原始变量时,更好的做法是什么:
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);
勒夫:有什么理由选择一个而不是另一个吗?
当前回答
如果你要修改变量的值,你应该传递一个指针。 尽管在技术上传递引用或指针是相同的,但在用例中传递指针更具有可读性,因为它“通告”了函数将更改值的事实。
其他回答
通过const引用传递,除非有原因你希望改变/保留你传递的内容。
在大多数情况下,这将是最有效的方法。
确保对不想更改的每个形参都使用const,因为这不仅可以防止您在函数中做一些愚蠢的事情,还可以很好地向其他用户指示函数对传入的值做了什么。这包括当你只想改变所指向的对象时,创建一个const指针…
如果你要修改变量的值,你应该传递一个指针。 尽管在技术上传递引用或指针是相同的,但在用例中传递指针更具有可读性,因为它“通告”了函数将更改值的事实。
这最终是主观的。到目前为止的讨论是有用的,但我不认为有一个正确或决定性的答案。这在很大程度上取决于风格指南和您当时的需求。
While there are some different capabilities (whether or not something can be NULL) with a pointer, the largest practical difference for an output parameter is purely syntax. Google's C++ Style Guide (https://google.github.io/styleguide/cppguide.html#Reference_Arguments), for example, mandates only pointers for output parameters, and allows only references that are const. The reasoning is one of readability: something with value syntax should not have pointer semantic meaning. I'm not suggesting that this is necessarily right or wrong, but I think the point here is that it's a matter of style, not of correctness.
可以时使用引用,必要时使用指针。 来自c++常见问题:“什么时候应该使用引用,什么时候应该使用指针?”
考虑一下c#的out关键字。编译器要求方法的调用者将out关键字应用于任何out参数,即使它已经知道它们是否存在。这是为了提高可读性。尽管在现代ide中,我倾向于认为这是语法(或语义)突出显示的工作。