在给函数使用原始变量时,更好的做法是什么:
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);
勒夫:有什么理由选择一个而不是另一个吗?
当前回答
这最终是主观的。到目前为止的讨论是有用的,但我不认为有一个正确或决定性的答案。这在很大程度上取决于风格指南和您当时的需求。
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++常见问题:“什么时候应该使用引用,什么时候应该使用指针?”
这最终是主观的。到目前为止的讨论是有用的,但我不认为有一个正确或决定性的答案。这在很大程度上取决于风格指南和您当时的需求。
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.
我的经验法则是:
如果你想对指针进行算术运算(例如,增加指针地址以遍历数组),或者如果你必须传递一个空指针,请使用指针。
否则使用引用。
指针:
可以被分配为nullptr(或NULL)。 在调用站点,如果你的类型本身不是指针,你必须使用&, 显式地修改对象。 指针可以被反弹。
引用:
不能为空。 一旦被束缚,就无法改变。 调用者不需要显式地使用&。有时这被认为是 不好,因为你必须去函数的实现看看 完成参数的修改。