Suppose I have a function that takes an argument of type T
.
It does not mutate it, so I have the choice of passing it by const reference const T&
or by value T
:
void foo(T t){ ... }
void foo(const T& t){ ... }
Is there a rule of thumb of how big T
should become before passing by const reference becomes cheaper than passing by value? E.g., suppose I know that sizeof(T) == 24
. Should I use const reference or value?
I assume that the copy constructor of T
is trivial. Otherwise, the answer to the question depends on the complexity of the copy constructor, of course.
I have already looked for similar questions and stumbled upon this one:
template pass by value or const reference or...?
However, the accepted answer (
https://stackoverflow.com/a/4876937/1408611 ) does not state any details,it merely states:
If you expect T always to be a numeric type or a type that is very
cheap to copy, then you can take the argument by value.
So it does not solve my question but rather rephrases it: How small must a type be to be "very cheap to copy"?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…