This might be an anti-climatic educated guess. I will welcome any other concrete example, however following general rules seems very reasonable.
Such limitation would not break any specific code but it would restrict domain of accepted programs. c++ is rather conservative when it comes to such changes, sometimes to a great pain. A notable example would be most vexing parse, what code would break if A a();
was interpreted as default-constructed A
? Yet it doesn't work this way to be backwards-compatible with c syntax. That's a rather PIA for syntax analysis.
c++ allows semantic redefinition of operator meaning for user defined types. I don't know if there is a good example of semantic redefinition for operator=
but there are some rather notable examples for other operators. boost::program_options "abuses" operator()
in a quite weird way, to create a concise syntax, and Eigen redefines comma operator semantics. Pointer-to-member operators are often redefined to do something non-standard since they are not used by default often. So sometimes it's useful.
I guess it might be useful with classes where operator=
has side effects, and is not necessarily meant to change the value in memory. I imagine that in some embedded development you can have Row
and Col
and you write row * col = LED_ON
or something along the lines. Another example from top of my head is an expression library, for example, there is no operator<=>
yet so operator=
could be used in it's place to evaluate stuff like (p ^ p) <=> p
.
operator=
is no special among operators and those are not really much more special than other member functions. If you write a code like this:
#include <iostream>
using namespace std;
struct A{
friend ostream& operator<<(ostream& out, A& a) { out << "A "; return out;}
};
int main() {
A a1, a2;
cout << a1=a2 << '\n';
return 0;
}
It will... break. That's because bitwise shift has precedence over =
. It requires parentheses around a1=a2
. This is to make a point that operator=
really has no special rights in the language.
The other thing is that you can overload those operators nearly as you wish, so writing
#include <iostream>
using namespace std;
struct A{
bool operator=(A& rhs) {return true;}
};
int main() {
A a1, a2;
cout << (a1=a2) << '\n';
return 0;
}
Is perfectly legal. Language provides operator with syntactic shortcuts and not much more. I don' think many complain that (a+b).method()
works, this is the same for (a+b).operator=()
.
Bonus: The example with int
s doesn't work because you cannot overload operators for primitive types and the default one is defined so it doesn't accept rvalues. It exhibits the behaviour that you seem to expect. Basically we are stripped from the freedom of redefining semantics of primitive type operators.
operator=
to be only called on l-values you might break preexisting code: stackoverflow.com/a/33784173/1938163&
can restrict a rvalue assignment. So some preexisting code used rvalue assignment? What's that for?