C++ 标准 : dereferencing NULL pointer to get a reference?

标签 c++ pointers reference null

我想知道 C++ 标准对这样的代码有何规定:

int* ptr = NULL;
int& ref = *ptr;
int* ptr2 = &ref;

实际上,结果是 ptr2 为 NULL,但我想知道,这只是一个实现细节还是标准中已明确定义?
在不同的情况下,对 NULL 指针的取消引用应该会导致崩溃,但在这里我取消引用它是为了获得一个由编译器作为指针实现的引用,因此实际上并没有对 NULL 进行实际的取消引用。

最佳答案

取消引用 NULL 指针是未定义的行为。

事实上,标准在注释(8.3.2/4“引用”)中指出了这种确切情况:

Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.


顺便说一句:有一次我知道 NULL 指针可以以明确定义的方式“取消引用”作为 sizeof 运算符的操作数,因为操作数sizeof 并未实际评估(因此取消引用从未实际发生)。

关于C++ 标准 : dereferencing NULL pointer to get a reference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2727834/

相关文章:

c++ - 如何在 C++ 头文件和源文件中使用 NumPy C-API?

c++ - 通过指针在函数之间传递 vector

c++ - 使用基于范围的 For 循环和 Char 指针字符串

C++ throw 类成员

c++ - 使用 OpenSSL 和 C++ 生成 sha256

c++ - 如何使用 Gecko 将 XUL 文档设置为应用程序的前端?

rust - rust 错误: value of type `std::vec::Vec<i32>` cannot be built from `std::iter::Iterator<Item=&i32>`

c++ - 推导 LValue 引用类型

c++ - 多线程可以访问同一个weak_ptr对象C++

c - 在 C 中使用指向 typedef 类型的指针作为指向原始类型的指针是未定义的行为吗?