带有临时对象和引用的 args 的规则 [英] rules with temporary objects and args by reference

查看:41
本文介绍了带有临时对象和引用的 args 的规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一堂课:

class A
{
 public:
 A() {}
};

和一个函数:

void x(const A & s) {}

而我这样做:

x(A());

有人可以向我解释有关通过引用传递临时对象的规则吗?就编译器允许的内容而言,您需要 const 的地方,是否发生隐式复制等.从玩弄来看,您似乎需要有意义的 const,但是否有关于所有这些的正式规则?

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?

谢谢!

推荐答案

有一个正式规则 - C++ 标准(如果您感兴趣,请参阅第 13.3.3.1.4 节)规定,临时文件只能绑定到常量引用- 如果您尝试使用非常量引用,编译器必须将此标记为错误.

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.

这篇关于带有临时对象和引用的 args 的规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆