what's the difference between

template<typename T>
auto add1(const T& a, const T& b)
{ return a + b; }

and

template<typename T>
auto add2(T a, const T& b)
{ return a += b; }

?

if you know the answer you are better than boost

Show thread

@pleb If you care about optimization you enable optimization

godbolt.org/z/TKdGv3ezv

so only difference is that can't pass const & in register across translation units, but if inlined there will be no difference, and LTO might fix it as well.

If you want to test for more complex classes, write one that counts constructions and run it with optimizations. A single instance will need to be constructed in both cases, but everything else the compiler can elide.

Follow

@pleb I gave the counter a try, and seems like I need {a+=b; return a;} for the optimizations to kick in, then for both cases there's a single copy in your example. If you pass a temporary as a first parameter though, you'll get a move instead of a copy with add2, and for that reason it's a general rule of thumb in modern c++: if you know you need a copy - pass by value. That said there is a bigger semantic difference there that I had in mind.

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.