rules with temporary objects and args by reference

我是研究僧i 提交于 2019-12-10 10:30:38

问题


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!


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/710807/rules-with-temporary-objects-and-args-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!