views:

187

answers:

3

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!

+8  A: 

Herb Sutter does a fine job explaining it here: http://www.gotw.ca/gotw/081.htm

+1  A: 

x() must either take a const reference to a temporary A, or x() must take an A by-value.

John Dibling
+9  A: 

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.

anon
Thanks - I missed 13.3... last time I was looking this up.
David Thornley