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

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

    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).

提交回复
热议问题