Hacker News new | ask | show | jobs
by cowlevel 24 days ago
It's not about that, it's about avoiding copying to a function parameter. If you want a function that adds a bunch of integers, you should write it as "int sum(vector<int> const&)" rather than "int sum(vector<int>)" because the latter will copy the whole array of numbers just to sum them and delete the copy, when you could have summed the original array with no downside. Arguably it should be span<int> though now that exists.
1 comments

If you just want to avoid a copy without adding a null state then it's the reference bit that makes all the difference. Whether that reference is a const reference or not does not matter for optimization, I think.
If you make it a non-const reference the compiler won't let you pass a result of another function call such as sum(get_daily_prices())
Sure, but I think that has less to do with optimizations and more to do with avoiding potential footguns. The standard could, in principle, allow temporaries to bind to non-const references (and IIRC older versions of Visual Studio did do such a thing).

And even without such a change, such a restriction is pretty easily worked around without a const reference with something like T&& temp = get_daily_prices(); sum(temp);. I don't think that'll result in different codegen than either passing a temporary to a const ref or allowing binding a temporary to a non-const ref.