临时对象最初是 const 吗?
这个代码是 UB 吗?
Is this code 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
的初始化由[dcl.init.ref]/5(粗体字):
The initialization of the reference a
is given by [dcl.init.ref]/5 (bold mine):
否则,如果初始化表达式
Otherwise, if the initializer expression
- 是一个右值(但不是位域)[...]
那么第一种情况下的初始化表达式的值和第二种情况下的转换结果称为转换后的初始化程序.如果转换后的初始值设定项是纯右值,则将其类型 T4 调整为类型cv1 T4" ([conv.qual]) 并应用临时实现转换 ([conv.rval]).p>
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{}
调整为const A
.
So it means that the type prvalue expression that initialize the reference, A{}
, is adjusted to const A
.
然后 [conv.rval] 状态:
T 类型的纯右值可以转换为 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();
是未定义的行为.
相关文章