假设,我想给一个函数传递一个可修改的参数,我应该怎么选择:通过指针传递还是通过引用传递?
Provided, I want to pass a modifiable parameter to a function, what should I choose: to pass it by pointer or to pass it by reference?
我问这个是因为我一直认为通过引用传递参数是最佳做法(1),但在检查了一些本地代码数据库后,我得出了一个结论,最常见的方法是(2).此外,该人本人 (Bjarne Stroustrup) 建议使用 (2).(1) 和 (2) 的 [dis] 优点是什么,还是只是个人喜好问题?
I am asking this because I always considered it the best practice to pass parameter by reference (1), but after examining some local code database, I came to a conclusion, that the most common way is (2). Moreover, the man himself (Bjarne Stroustrup) recommends using (2). What are the [dis]advantages of (1) and (2), or is it just a matter of personal taste?
在以下情况下,我更喜欢引用而不是指针:
I prefer a reference instead of a pointer when:
虽然有人说引用和常量引用之间的区别对很多人来说太微妙了,并且在调用方法的代码中是不可见的(即,如果您阅读通过引用传递参数的调用代码,您看不到它是常量引用还是非常量引用),因此您应该将其设为指针(以在调用代码中明确表示您要提供变量的地址,因此你的变量的值可能会被被调用者改变).
Some people say though that the difference between a reference and a const reference is too subtle for many people, and is invisible in the code which calls the method (i.e., if you read the calling code which passes a parameter by reference, you can't see whether it's a const or a non-const reference), and that therefore you should make it a pointer (to make it explicit in the calling code that you're giving away the address of your variable, and that therefore the value of your variable may be altered by the callee).
我个人更喜欢参考,原因如下:
I personally prefer a reference, for the following reason:
[1.] 意味着让可变性对调用者可见并不重要,因为调用者应该已经(通过其他方式)了解子例程的作用(包括它将修改参数的事实).
[1.] implies that making the mutability visible to the caller doesn't matter much, because the caller should already (by other means) understand what the subroutine does (including the fact that it will modify the parameter).
[2.] 暗示如果它是一个指针,那么子例程应该处理参数是空指针的可能性,这可能是额外的和 IMO 无用的代码.
[2.] implies that if it's a pointer then the subroutine should handle the possibility of the parameter's being a null pointer, which may be extra and IMO useless code.
此外,每当我看到一个指针时,我都会想,谁将删除它,什么时候?",所以无论何时/何地所有权/生命周期/删除都不是问题,我更喜欢使用引用.
Furthermore, whenever I see a pointer I think, "who's going to delete this, and when?", so whenever/wherever ownership/lifetime/deletion isn't an issue I prefer to use a reference.
就其价值而言,我习惯于编写常量正确的代码:因此,如果我声明一个方法具有非常量引用参数,那么它是非常量的事实很重要.如果人们不编写 const 正确的代码,那么可能更难判断一个参数是否会在子例程中被修改,而另一种机制的参数(例如指针而不是引用)会更强一些.
For what it's worth I'm in the habit of writing const-correct code: so if I declare that a method has a non-const reference parameter, the fact that it's non-const is significant. If people weren't writing const-correct code then maybe it would be harder to tell whether a parameter will be modified in a subroutine, and the argument for another mechanism (e.g. a pointer instead of a reference) would be a bit stronger.
这篇关于将可修改的参数传递给 C++ 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!