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

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

    If the most straightforward implementation of the function involves modifying the parameter value locally, then it makes sense to pass it by value rather than by const reference

    For example, the one line version of strcpy:

    char *strcpy(char *dest, const char *src)
    {
       while (*dest++ = *src++);
    
       return s1;
    }
    

    If you took in the pointers as const references, you would need to copy them to temporaries in the body of your program, rather than letting the paramater passing mechanism do it for you.

提交回复
热议问题