本文介绍了是否有任何特定的情况下,pass-by-value优先于C ++中的pass-by-const引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到他们在概念上是平等的。实际上,有任何场合

  foo(T t)
pre>

优于

  foo(const T& t) 

?为什么?






感谢您的回答, 和之间的区别。 by-val



我曾经持有的观点认为by-const-ref可以替代call-value中的值,因为即使Herb Sutter和Bjarne说他们在概念上是相等的,而by ref(是const)意味着更快。直到最近,我在某处阅读过某些地方,在某些情况下可能会更好地优化旁注。



那么什么时候和如何?

解决方案

内置类型和小对象(例如STL迭代器)通常应通过值传递。



这部分是为了增加编译器的优化机会。令人惊讶的是,编译器很难知道引用参数是否是另一个参数或全局别名 - 它可能必须通过函数从内存中重读对象的状态多次,以确保该值没有改变。 / p>

这是C99的 restrict 关键字的原因(同样的问题,但是有指针)。


I read that they are conceptually equal. In practice, is there any occasion that

foo(T t)

is preferred over

foo(const T& t)

? and why?


Thanks for the answers so far, please note I am not asking the difference between by-ref and by-val.

Actually I was interested in the difference between by-const-ref and by-val.

I used to hold the oipinion that by-const-ref can replace by-value in call cases since even Herb Sutter and Bjarne said they are conceptually equal, and "by ref"(be it const) implies being faster. until recently, I read somewhere that by-val may be better optimized in some cases.

Then when and how?

解决方案

Built-in types and small objects (such as STL iterators) should normally be passed by value.

This is partly to increase the compiler's opportunities for optimisation. It's surprisingly hard for the compiler to know if a reference parameter is aliasing another parameter or global - it may have to reread the state of the object from memory a number of times through the function, to be sure the value hasn't changed.

This is the reason for C99's restrict keyword (the same issue but with pointers).

这篇关于是否有任何特定的情况下,pass-by-value优先于C ++中的pass-by-const引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 22:08