临时对象最初是const吗? [英] Is temporary object originally const?

查看:92
本文介绍了临时对象最初是const吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码是UB吗?

struct A
{
 void nonconst() {}
};

const A& a = A{};
const_cast<A&>(a).nonconst();

换句话说,(临时)对象最初是const吗?我浏览了该标准,但找不到答案,因此希望引用相关部分.

In other words, is the (temporary) object originally const? I've looked through the standard but cannot find an answer so would appreciate quotations to relevant sections.

:对于那些说A{}不是const的人,那么您可以做A{}.nonconst()吗?

for those saying A{} is not const, then can you do A{}.nonconst() ?

推荐答案

引用a的初始化由

The initialization of the reference a is given by [dcl.init.ref]/5 (bold mine):

否则,如果初始化表达式为

Otherwise, if the initializer expression

  • 是右值(但不是位域)[...]

然后,在第一种情况下的初始值设定项表达式的值,在第二种情况下的转换结果称为转换后的初始值设定项. 如果转换后的初始值设定项是prvalue,则将其类型T4调整为"cv1 T4"([conv.qual]),并应用临时实现转换([conv.rval]). >

then the value of the initializer expression in the first case and the result of the conversion in the second case is called the converted initializer. If the converted initializer is a prvalue, its type T4 is adjusted to type "cv1 T4" ([conv.qual]) and the temporary materialization conversion ([conv.rval]) is applied.

因此,这意味着将初始化引用A{}的类型prvalue表达式调整为const A.

So it means that the type prvalue expression that initialize the reference, A{}, is adjusted to const A.

然后 [conv.rval] 状态:

类型T的prvalue可以转换为类型T的xvalue. 此转换将初始化类型T的临时对象([class.temporary]).

A prvalue of type T can be converted to an xvalue of type T. This conversion initializes a temporary object ([class.temporary]) of type T.

因此绑定到引用的临时对象的类型与调整后的prvalue类型相同:const A.

So the type of the temporary object, bound to the reference is the same as the adjusted prvalue type: const A.

所以代码const_cast<A&>(a).nonconst();未定义的行为.

这篇关于临时对象最初是const吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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