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; }

?

Follow

if you know the answer you are better than boost

ยท ยท 2 ยท 0 ยท 0

@namark well my C++ is a little rusty but functionally they should be relatively equivalent as far as I can tell. The second one may be a bit slower as it reassigns a variable with function level scope before returning it (and the scope therefore being dropped)... but aside from the second one being a little inefficient they should behave the same.

@freemo Not entirely sure about performance characteristics myself, good hunch that the differences are minor, but as far as I know add2 can actually be faster in some cases, if you take optimizations in consideration, and the reason it could be slower is not at all what you suggest, it usually is about construction and copying of objects.

There is a notable functional difference though, but not gonna hint too hard for now.

@namark id be curious to see benchmarks on it to suggest the differences. But yea i cant be 100% on the performance here, instinct tells me 2 is slower, but compiler magic can do all sorts of stuff I dont anticipate.

@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.

@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.