If we have a class with custom +, -, *, / and = operators is there any particular reason why the compiler can't automatically generate operators +=, -=, *=, /= like this:
#include <iostream>
usingnamespace std;
class Foo
{
public:
Foo& operator += (const Foo& foo)
{
cout << "adding";
return *this;
}
};
// if you template it, the template will work for any type 'T'
template <typename T>
inline T operator + (const T& l, const T& r)
{
T v(l);
return v += r;
}
int main()
{
Foo a, b;
Foo c;
c = a + b; // invokes the template +, which calls Foo::operator +=
cin.get();
}
struct MyInt{
int x;
MyInt& operator += (const MyInt& a) {
x += a.x;//no copying
return *this;
}
MyInt operator + (const MyInt& a) {
MyInt b = *this;//one copy
return b+=a;//one copy
}
}
+= though + :
1 2 3 4 5 6 7 8 9 10 11
struct MyInt{
int x;
MyInt operator + (const MyInt& a) {
MyInt b;//not really a copy.. but does use memory and call a constructor
b.x = x+a.x;
return b;//a copy
}
MyInt& operator += (const MyInt& a) {
return *this = *this + bar;//copy and a copy inside operator +
}
}
Though now that I think about it, I'm not sure whether I make sense.. Also, I really have no idea how smart compilers are.
@Athar I thought it was the kind of thing Boost would have...
@hamsterman Well the second one seems a little better, though as you say, MyInt b has the potential to require about half the operations used by a copy if the constructor sets all the member variables to defaults.
Presumably, in the right circumstances, the copies caused by returns in both cases may be removed by RVO.