is there any specific case where pass-by-value is preferred over pass-by-const-reference in C++?

后端 未结 15 1927
臣服心动
臣服心动 2020-12-06 08:03

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

foo(T t) 

is preferred over

foo(const T&         


        
15条回答
  •  囚心锁ツ
    2020-12-06 08:05

    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.

提交回复
热议问题