问题描述
我遇到了这个.
根据样式指南,只允许 const 引用作为参数.(我是这么理解的)
According to the style guide, only const references are allowed as parameters. (That's what I understood)
虽然,我似乎不喜欢这种方法.
Although, I don't seem to like that approach.
评论?
推荐答案
以下是几条经验法则,可用于在您的选择之间做出决定:
Here are a couple of rules of thumb that can be useful when deciding between your options:
如果您不需要修改传入函数的对象,请考虑对象的大小是否小于或等于指针的大小.如果是,则按值传递;否则,通过常量引用.
If you don't need to modify the object being passed into the function, consider whether the size of the object is less than or equal to the size of a pointer. If so, pass by value; otherwise, pass by const reference.
如果您确实需要修改被传递给函数的对象,请考虑参数是否是可选的(即,null 是一个有效的参数).如果是,则通过指针传递;否则,通过非常量引用传递.
If you do need to modify the object being passed into the function, consider whether the parameter is optional (that is, null is a valid argument). If so, pass by pointer; otherwise, pass by non-const reference.
这篇关于是通过引用来传递常量而不是非常量传递引用更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!