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

后端 未结 15 1890
臣服心动
臣服心动 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:25

    Another case that hasn't been mentioned is heavy use of the object. Let's say you pass a struct with 5 ints as members. If you are going to be accessing all 5 quite a lot in your function, there comes a point when the dereference cost outweighs the copy cost. However, you'd have to run a profiler to know when that is.

    I should point out, though, that things like STL containers, which allocate memory on the heap, should almost never be passed by value if avoidable, because heap allocation is very slow compared to stack allocation.

提交回复
热议问题