c++ - 通过取消引用 NULL 指针来分配引用

标签 c++ pointers reference undefined-behavior null-pointer

int&  fun()
{
    int * temp = NULL;
    return *temp;
}

在上述方法中,我正在尝试解除对 NULL 指针的引用。当我调用此函数时,它不会给出异常。我发现当返回类型是按引用时,如果它是按值,则它不会给出异常。即使将 NULL 指针的取消引用分配给引用(如下行),它也不会给出。

int* temp = NULL:
int& temp1 = *temp;

这里我的问题是编译器不会在引用的情况下进行取消引用吗?

最佳答案

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

未定义的行为意味着任何事情都可能发生,因此无法为此定义行为。

诚然,我将第 n 次添加此 C++ 标准引用,但似乎有必要。

关于未定义的行为,

C++ 标准第 1.3.24 节规定:

Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

注意:
另外,请注意:
使用返回的引用或指向函数内部局部变量的指针也是未定义行为。您应该使用 new 在 freestore(heap) 上分配指针,然后返回指向它的引用/指针。

编辑:
正如@James McNellis,在评论中适当指出,
如果不使用返回的指针或引用,则行为定义明确

关于c++ - 通过取消引用 NULL 指针来分配引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6716091/

相关文章:

c++ - 为什么要使外部变量成为引用?

c - 为什么可以将 int 的地址视为指向 int 的指针?

c++ - Eratosthenes 实现筛法

c++ 在已知位置插入 vector

c++ - 使用尽可能多的CPU核心编写 super UDP服务器

c++ - 调用模板化成员函数与模板化全局函数在通用工厂中创建对象

c++ - 复制并取消 int 数组

c++ - SecVerifyTransformCreate 内存泄漏?

c++ - 在 C++ 中声明指针时,我将星号放在哪里有关系吗?

c++ - C++:在函数的参数上下文中, `const T &`和 `T &&`有什么区别?