Is it allowed to cast away const on a const-defined object as long as it is not actually modified?(只要未实际修改,是否允许在 const 定义的对象上丢弃 const?)
问题描述
是否允许:
const int const_array[] = { 42 };
int maybe_inc(bool write, int* array) {
if (write) array[0]++;
return array[0];
}
int main() {
return maybe_inc(false, const_cast<int *>(const_array));
}
特别是,是否可以抛弃 const_array
的 const 性,它被 定义 为 const,只要对象没有被实际修改,如例子?
In particular, is it OK to cast-away the constness of const_array
, which was defined as const, as long as the object is not actually modified, as in the example?
推荐答案
是的.这是完全合法的.(这是危险的,但它是合法的.)如果你(试图)修改一个声明为 const 的对象,那么行为是未定义的.
Yes. This is entirely legal. (It is dangerous, but it is legal.) If you (attempt to) modify a an object declared const, then the behaviour is undefined.
来自 n4659(其中是 C++17 的最后草稿),第 10.1.7.1 节 [dcl.type.cv] 第 4 段:
From n4659 (which is the last draft of C++17), section 10.1.7.1 [dcl.type.cv] para 4:
除了可以修改任何声明为 mutable (10.1.1) 的类成员外,任何在 const 对象的生命周期 (6.8) 期间修改它的尝试都会导致未定义的行为
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++17 开始的,但所有版本的 C++ 都是如此.
My emphasis. That is from C++17, but this has been true of all versions of C++.
如果您查看关于 const_cast
的部分,有一条说明
If you look at the section on const_cast
there is a note that
[ 注意:根据对象的类型,通过指针、左值或指针进行写操作从 const_cast 产生的数据成员丢弃 const-qualifier76 可能会产生 undefined行为 (10.1.7.1).——尾注]
[ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier76 may produce undefined behavior (10.1.7.1). — end note ]
注释不是规范的,但这强烈暗示获取非常量引用或指向 const 对象的指针是合法的.是不允许写入.
Notes are not normative, but this strongly implies that obtaining a non-const reference or pointer to a const object is legal. It is the write that is not allowed.
这篇关于只要未实际修改,是否允许在 const 定义的对象上丢弃 const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:只要未实际修改,是否允许在 const 定义的对象上丢弃 const?


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01