is there any specific case where pass-by-value is

2020-02-05 09:38发布

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?

标签: c++
15条回答
戒情不戒烟
2楼-- · 2020-02-05 10:24
  1. As previously noted, prefer pass-by-value if you want a copy of the object in your function.
  2. I usually use pass-by-value if copying T is cheaper than creating/copying a reference, e.g. T=char, T=short. The benefit here could be platform dependent, and you'd probably still want const where applicable to help the optimizer.
查看更多
够拽才男人
3楼-- · 2020-02-05 10:28

The reason pass by const reference and by value are conceptually the same is that neither can modify the original.

Normally, I am big fan of pass by value because it creates code that avoids many of the complexities that occur when multiple threads are sharing access to common data.

That said, it does potentially make you're code slower. My take in the past has always been to prefer pass by value unless I know their is (or will be) a performance problem by doing so. I may have to modify this slightly to include pass by const reference as an even better option.

查看更多
beautiful°
4楼-- · 2020-02-05 10:29

In addition, foo(T t) is normally used when T is a simple type (int, bool, etc).

查看更多
登录 后发表回答