只要未实际修改const定义的对象,是否可以将其抛弃? [英] Is it allowed to cast away const on a const-defined object as long as it is not actually modified?

查看:97
本文介绍了只要未实际修改const定义的对象,是否可以将其抛弃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否允许以下​​内容:

Is the following allowed:

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,只要对象没有被实际修改(如示例中所示)?

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:


除了任何类成员声明为可变的(10.1.1 ),可以对其进行修改,在其生存期(6.8)内尝试修改const对象都会导致未定义的行为



<我的重点。那是从C ++ 17开始的,但是在所有C ++版本中都是如此。

My emphasis. That is from C++17, but this has been true of all versions of C++.

如果您查看 const_cast 的部分, code>有一个注释,

If you look at the section on const_cast there is a note that


[注意:根据对象的类型,通过指针进行写操作,由const_cast抛出const-qualifier76导致的指向数据成员的左值或指针
可能会产生未定义的
行为(10.1.7.1)。 — end note]

[ 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引用或指向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定义的对象,是否可以将其抛弃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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