gpt4 book ai didi

c++ - 具体来说,标准在哪里规定修改 const 对象是未定义的行为?

转载 作者:行者123 更新时间:2023-12-01 19:39:46 25 4
gpt4 key购买 nike

众所周知,以下示例表现出未定义的行为:

T const x = T();
T& r = any_suitable_conversion_to_Tref(x); // fine
r = T(); // UB

cppreference 已针对 const_cast 确认了这一点:

const_cast makes it possible to form a reference or pointer to non-const type that is actually referring to a const object or a reference or pointer to non-volatile type that is actually referring to a volatile object. Modifying a const object through a non-const access path and referring to a volatile object through a non-volatile glvalue results in undefined behavior.

但是,它没有提到例如c 风格转换,并且它不引用标准(cppreference 通常从不引用)。

C++ 标准到底在哪里禁止这样做?

最佳答案

C++17 标准在 [dcl.type.cv] 10.1.7 第 10 章“声明”中进行了说明:

  1. Except that any class member declared mutable (10.1.1) can be modified, any attempt to modify a const object during its lifetime (6.8) results in undefined behavior.

关于c++ - 具体来说,标准在哪里规定修改 const 对象是未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61939725/

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