better but still not quite there. There is a way on most current compilers to get rid of that temporary and make this efficient. Its such an important optimization that it has been given a name. Its called the return value optimization.
Code:
// Yours...
Sample operator+(const Sample & rhs, const Sample & lhs)
{
Sample result;
result.first = rhs.first + lhs.first;
result.second = rhs.second + lhs.second;
return result;
}
// now mine...
const Sample operator +(const Sample& lhs, const Sample& rhs)
{
return Sample( (lhs.first+rhs.first),(lhs.second+rhs.second));
}
This assumes that you have a Sample(int,int) constructor but with a class like that one that constructor would make perfect sense and makes writing operator + a doddle.Notice how in your func you have a named object. Named objects cannot be eliminated even if they are not used. My func suffers from no such problem so is efficient as long as the compiler supports the RVO otherwise it offers little over yours.
edit...
Also you should return a reference to the current object in operator +=.This will allow cascading.