class A
{
public:
A(int a=0) {}
};
int f0() {int i(9); return i;}
A f1() {return A();}
int main()
{
f0()=9;//compile error {expected}
f1()=9;//fine, ctor is not explicit {cannot understand}
}
I am not able to get this behaviour. Are not temporaries supposed to be non-modifiable? That's the reason they cannot be bound to a non-const reference right?
You can call non-const member functions on temporary objects.
f1()=9; is the same as f1().operator=(A(9));. The constructor is used to turn 9 into an A. operator= is a member of A so you can use it on the temporary object.
int's operator= isn't a member. Nothing can be a member of int because int is not a class so that why you get an error.
so this essentially means you are allowing modification of a temporary, which brings to the second question, why then are non-const references not allowed to a temporary? I thought it was precisely for this reason (modification stuff).
also
You can call non-const member functions on temporary objects.
is more like "you can also call non-const....." right?
why then are non-const references not allowed to a temporary?
In most cases it's not useful to be able to modify temporary objects because it will no longer exist at the end of the statement anyway. I think the reason why they don't allow it is because in most cases it's an error so it's better to be able to give an error message. That way the error can easily be fixed right away. I'm not sure why member functions is an exception.
is more like "you can also call non-const....." right?
which brings to the second question, why then are non-const references not allowed to a temporary? I thought it was precisely for this reason (modification stuff).
Annoying isn't it.
However under C++11 - you can bind them to a RValue reference - which
will allow you to change them (so you can use move semantics on them)
yes it is annoying or confusing to see one of user-defined and built-in types get more/different support than the other when the philosophy has always been otherwise (as is evident throughout Stroustrup's reflections). But it's nice to know these as caveats.