为什么在使用空引用参数时崩溃,而不是在初始化参数时崩溃?

Why does this crash at use of a null reference parameter, and not where it is initialized?

本文关键字:崩溃 参数 初始化 引用 为什么      更新时间:2023-10-16

我在gcc 4.8.3和msvc v120中测试了以下代码。

#include <iostream>
using std::cout;
void bar(int &x)
{
    cout << "barn";
    int y = x; // Crash here...
}
void foo(int *x)
{
    cout << "foon";
    bar(*x); // No crash here...
}
int main()
{
    foo(0);
    return 0;
}
输出:

$ ./test
foo
bar
Segmentation fault (core dumped)

我预计它会在*x上崩溃,但是当int引用被解引用时它崩溃了。它是用以下g++ -O0 -std=c++11 -pedantic -o test test.cpp编译的。有人能解释一下这种行为吗?如何在不解引用空指针的情况下初始化引用?

在未定义行为的情况下,什么都无法预测。任何事情都有可能发生。该程序可以按照您的期望运行,也可以擦除您的硬盘!!