具体来说,标准在哪里声明修改 const 对象是未定义的行为?
Where, specifically, does the standard state that modifying a const object is undefined behaviour?
众所周知,以下示例会表现出未定义的行为:
T const x = T();
T& r = any_suitable_conversion_to_Tref(x); // fine
r = T(); // UB
const_cast
已由 cppreference 确认:
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 标准在第 10 章 "Declarations" [dcl.type.cv] 10.1.7 下声明:
- 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.
众所周知,以下示例会表现出未定义的行为:
T const x = T();
T& r = any_suitable_conversion_to_Tref(x); // fine
r = T(); // UB
const_cast
已由 cppreference 确认:
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 标准在第 10 章 "Declarations" [dcl.type.cv] 10.1.7 下声明:
- Except that any class member declared
mutable
(10.1.1) can be modified, any attempt to modify aconst
object during its lifetime (6.8) results in undefined behavior.