Why is that I can assign to a temporary value of a class type?
#include<complex>
std::complex<double> f() {return 0.;}
double g() {return 0.;}
int main() {
f() = 0.; // compiles !?
g() = 0.; // doesn't compile
}
https://godbolt.org/z/3fx9d5Yac
I think that the builtin behavior is the more natural.
Is this a defect on the way assignment is implemented is implemented in certain classes?
What can be done to the class definition (assuming I have control over the class) to prevent this unexpected behavior and behave like builtins? (assuming one can control the class)
In my experiments adding const to the result type solves the problem, but this is uncostumary and also prevent moves AFAIK, e.g. for larger objects.
const std::complex<double> f() {return 0.;}
One can argue whether the behavior is correct in the language, however it creates very misleading interfaces.
class complex_arg {
double r_;
double phi_;
public:
std::complex<double> value() const {return r_*exp(phi_*std::complex<double>{0, 1});}
};
int main() {
complex_arg ca;
ca.value() = std::complex<double>(1000., 0.); // accepted by the compiler
assert( ca.value() != std::complex<double>(1000., 0.) ); // what!
}
I see only one way out, but it requires modifying the class and it doesn't scale well (to large classes that can be moved).
const std::complex<double> value() const