gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:37:22 26 4
gpt4 key购买 nike

这个代码是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/55828305/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com