gpt4 book ai didi

c++ - 取消引用无效指针但不使用结果是 C++ 中的未定义行为吗?

转载 作者:搜寻专家 更新时间:2023-10-31 00:30:46 25 4
gpt4 key购买 nike

考虑以下 C++ 代码:

int main() {
int* ptr; // Deliberately uninitialized
(void) *ptr; // Dereference, do not use result
}

此代码是否会导致未定义的行为?我假设答案是"is",即使 *ptr 的值实际上并未在任何地方使用。规范中是否有特定部分可以保证这一点?

(如果这是重复的,我深表歉意,但我似乎无法在网站上找到任何其他专门询问此问题的内容。)

最佳答案

简单地取消引用尚未分配或标记为只读 的指针会导致CPU 内存管理单元中出现硬件异常。因此,即使您不使用通过取消引用包含随机值的指针而返回的任何垃圾值,也不能保证 CPU 会从此类事件中返回。

但是,根据 ISO C++11 标准,声明为未初始化的指针必须有一个奇异值。所以未初始化指针的值不是未定义,因为它不是垃圾。

然而,标准规定,除了用非奇异值覆盖奇异值外,对此类奇异值指针的大多数操作都是未定义的em>:

24.2.1 In general [ iterator.requirements.general ]

5 [ Example: After the declaration of an uninitialized pointer x (as with int* x;), x must always be assumed to have a singular value of a pointer. — end example ] Results of most expressions are undefined for singular values; the only exceptions are destroying an iterator that holds a singular value, the assignment of a non-singular value to an iterator that holds a singular value, and, for iterators that satisfy the DefaultConstructible requirements, using a value-initialized iterator as the source of a copy or move operation. [ Note: This guarantee is not offered for default initialization, although the distinction only matters for types with trivial default constructors such as pointers or aggregates holding pointers. — end note ] In these cases the singular value is overwritten the same way as any other value. Dereferenceable values are always non-singular.

关于c++ - 取消引用无效指针但不使用结果是 C++ 中的未定义行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35711301/

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