Is temporary object originally const?(临时对象最初是 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();
是未定义的行为.
这篇关于临时对象最初是 const 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:临时对象最初是 const 吗?


基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01