内置类型/很小的对象(包括int64、std::string_view),传值,对优化有好处,可以直接走寄存器,不用走内存。
如果传递常量引用、指针,编译器需要知道这个东西对应的内存在caller、callee处是怎么被引用的才能优化得更好,
不然只能采用保守的优化(因为别的不知道的变量可能也指向了对应的内存,aliasing)。
尤其是对于接口中的参数,编译器可能只知道接口的caller、callee二者之一的情况。
CppCoreGuidelines也说得比较清楚
F.16: For “in” parameters, pass cheaply-copied types by value and others by reference to const
Reason Both let the caller know that a function will not modify the argument, and both allow initialization by rvalues.
What is “cheap to copy” depends on the machine architecture, but two or three words (doubles, pointers, references) are usually best passed by value. When copying is cheap, nothing beats the simplicity and safety of copying, and for small objects (up to two or three words) it is also faster than passing by reference because it does not require an extra indirection to access from the function.
Should I use call-by-value or call-by-reference?
That depends on what you are trying to achieve:
If you want to change the object passed, call by reference or use a pointer; e.g. void f(X&); or void f(X*);
If you don't want to change the object passed and it is big, call by const reference; e.g. void f(const X&);
Otherwise, call by value; e.g. void f(X);
What do I mean by "big"? Anything larger than a couple of words.
--
修改:z16166 FROM 222.129.205.*
FROM 222.129.205.*