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

标签 c++ pointers language-lawyer

考虑以下 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/

相关文章:

c - strcat 给出意外结果

c - C中的动态内存分配二维数组

c++ - std::reference_wrapper 的问题

c - 将结构的元素添加到同一结构的数组时出错

c - 是否可以通过成员地址访问超过结构的大小,并分配足够的空间?

c++ - 为什么 std::numeric_limits<seconds>::max() 返回 0?

c++ - 如何制作存储在数组中的STL对象的拷贝?

c++ - Google Protocol Buffer ,如何设置自定义类型的字段?

c++ - boost::asio io_service::run_one 导致段错误

c++ - 虚函数调用