gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:09:28 25 4
gpt4 key购买 nike

最近我决定深入研究 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.

关于C++17 标准 - 抛弃 const of static,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54744736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com