say I have a class:
class A
{
public:
A() {}
};
and a function:
void x(const A & s) {}
and I do:
x(A());
could someone please explain to me the rules regarding passing temporary objects by reference? In terms of what the compiler allows, where you need const, if an implicit copy happens, etc. From playing around, it seems like you need the const which makes sense, but is there a formal rule regarding all this?
Thanks!
There is a formal rule - the C++ Standard (section 13.3.3.1.4 if you are interested) states that a temporary can only be bound to a const reference - if you try to use a non-const reference the compiler must flag this as an error.
x() must either take a const reference to a temporary A, or x() must take an A by-value.
Herb Sutter does a fine job explaining it here: http://www.gotw.ca/gotw/081.htm