rules with temporary objects and args by reference

2019-05-27 03:09发布

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!

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-05-27 03:48

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.

查看更多
一夜七次
3楼-- · 2019-05-27 03:58

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

查看更多
Rolldiameter
4楼-- · 2019-05-27 04:07

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

查看更多
登录 后发表回答