为什么在使用空引用参数时崩溃,而不是在初始化参数时崩溃?
Why does this crash at use of a null reference parameter, and not where it is initialized?
我在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
编译的。有人能解释一下这种行为吗?如何在不解引用空指针的情况下初始化引用?
在未定义行为的情况下,什么都无法预测。任何事情都有可能发生。该程序可以按照您的期望运行,也可以擦除您的硬盘!!
相关文章:
- 如果可推导类型上有替换,可变参数模板类型推导会使编译器崩溃
- 对 const 引用参数使用默认值会导致崩溃
- C++具有移动语义的可变参数工厂会导致运行时崩溃
- 由于调用 std::condition_variable 后参数无效而导致应用程序崩溃
- 变量参数崩溃的 C 函数
- 为什么我的SFML将SF ::纹理作为参数传递到函数时会不断崩溃
- 调用从 lambda 作为模板参数传递的成员函数指针会崩溃
- 为什么对齐的参数编译正确,但在运行时崩溃
- jvm在尝试将TCHAR类型发送到接受字符串作为参数的java函数时崩溃
- 传递一个向量作为参数并使用它,它为什么会崩溃
- OpenCL内核因特定参数而崩溃
- 如何确保当无效字符串作为参数传递时posix_time_zone构造函数不会崩溃
- 静态 c++ 对象中的 JNI 环境指针并调用连续两次使用字符串参数的 Java 函数会使 JVM 崩溃
- 尝试使二叉搜索树适应两个参数,崩溃(C++)
- IDL CALL_EXTERNAL在向C++传递参数时崩溃
- CRT参数验证使多线程调试程序崩溃
- LLVM JIT教程代码崩溃与简单的参数化函数.为什么
- 为什么我的命令行参数处理崩溃我的程序
- 为什么在使用空引用参数时崩溃,而不是在初始化参数时崩溃?
- Android JNI错误:调用带有布尔参数的函数会导致崩溃