只要未实际修改,是否允许在 const 定义的对象上丢弃 const? [英] Is it allowed to cast away const on a const-defined object as long as it is not actually modified?

查看:25
本文介绍了只要未实际修改,是否允许在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆