c++ - 临时对象最初是 const 吗?

标签 c++ constants language-lawyer undefined-behavior temporary-objects

这个代码是UB吗?

struct A
{
 void nonconst() {}
};

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

换句话说,(临时)对象最初是 const 吗?我已经仔细阅读了标准,但找不到答案,因此希望能引用相关部分的内容。

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

最佳答案

引用的初始化a[dcl.init.ref]/5 给出(大胆的矿山):

Otherwise, if the initializer expression

  • is an rvalue (but not a bit-field)[...]

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 .

然后 [conv.rval]状态:

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.

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

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

关于c++ - 临时对象最初是 const 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54334861/

相关文章:

c++ - 通过placement-new手动构造一个平凡的基类

c++ - 如何获取特定 WCHAR 字符的代码点?

C++ const 双指针

javascript - 为什么 Node.js 中的事件不使用常量?

c++ - 定义常量数据成员

c++ - 没有前向声明的嵌套函数模板实例在 GCC 上编译,但不在 clang 上编译

c# - 本地化应用名称

javascript - 是否可以连接到节点。带有 C++ 客户端的 js websocket 服务器

c++ - 多项式类在处理重载运算符时崩溃=

c++ - C++ 中指针运算的 a+i 和 &a[i] 有什么区别?