string
doesn't need to be passed as a constant or by reference. It's just more efficient to do so if the function doesn't need to modify or preserve a copy of the string anyway, because string
s can be arbitrarily huge, and passing by value would require copying their contents; not fun if it's a string
made by slurping a 1 GB file, so calling the function involves allocating and populating a solid 1 GB of new memory.
Passing by const
reference, rather than mutable reference, is to avoid surprises. From the caller's perspective, const
reference and passing by value give the same guarantees: The caller's string
won't change. But if the function accepts a mutable reference, the caller's string
might change as a result of the call, and now they need to back it up if they need to preserve the original value.
None of that means you can't pass string
in other ways. If you need a personal copy of the string
(to store beyond the length of the call, or to mutate without affecting the caller), accept it by value instead of const
reference (it will be more efficient than receiving const
reference, then copying, in the case where the caller passes you an r-value). If you need to be able to mutate the caller's value, accept by mutable reference. But if you don't need to do either, the default should be const
reference; it's fast, and it simplifies the API for the caller, who doesn't need to worry about their arguments getting changed.
This optimization just isn't relevant for int
though. Where a string
can be anywhere from a handful of bytes to GB of data, an int
is a fixed size (implementation dependent, but typically 2-4 bytes), so the cost of copying it in by value is on the same order of magnitude as the cost of passing the reference (likely slightly cheaper than passing a reference actually, since the reference both reduces memory locality and is usually implemented as a pointer, which is often larger than the int
itself).
Point is, you have all the same options with int
as with string
. It's just that you need to be more careful about copies with string
, because it can bloat your memory usage and slow your code; no matter how you pass int
, it's not going to make a huge difference.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…