C++17 标准 - 抛弃 const of static

C++17 Standard - Cast away const of static

最近我决定深入研究 C++ 标准并检查某些代码片段是否定义明确以及在标准中的何处可以找到这些定义。由于标准很难正确(尤其是如果您不习惯),我想验证一下我的假设是否正确。

我遇到了以下示例(这显然是个坏主意)。它编译得很好(使用 g++ 8.2.1)但在执行期间出现 SEGFAULT:

#include <iostream>

static const int staticInt = 23;

int main () {
    int &localInt = const_cast<int &>(staticInt);
    localInt = 11;
    std::cout << staticInt << std::endl;
    return 0;
}

因此,我搜索了标准(顺便说一句,我使用了 open-std 上的工作草案)并找到了第 6.8.10 段:

Creating a new object within the storage that a const complete object with static, thread, or automatic storage duration occupies, or within the storage that such a const object used to occupy before its lifetime ended, results in undefined behavior.

我说的对吗,这一段适用于给定的示例?如果不是,我还应该看哪里?

这是未定义的行为,因为在使用 const_cast 变量后试图修改 const 变量。

来自 n4659 的引用,C++17 的最终工作草案。 本例相关段落为:

8.2.11 Const cast [expr.const.cast]
...
6 [ 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-qualifier may produce undefined behavior. —end note ]

本节还与 const 个对象相关:

10.1.7.1 The cv-qualifiers [dcl.type.cv]
...
4 Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior.