gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:10:39 25 4
gpt4 key购买 nike

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/

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