【发布时间】:2017-08-02 23:05:18
【问题描述】:
我无法解释为什么 C++ 中的以下代码构造即使使用 -Wall 选项也没有给出任何编译错误或警告。
假设有一个头文件,referencesTest.hpp,其中对 int 的引用是使用 extern 声明的:
#ifndef REFERENCES_TEST_HPP
#define REFERENCES_TEST_HPP
extern int &refToInt;
#endif /* REFERENCES_TEST_HPP */
在相应的源文件 referencesTest.cpp 中,我们定义了引用但未初始化,我们尝试在运行时为其分配一个值,如下所示:
#include "referencesTest.hpp"
//Why no error/warning is raised here ?
int &refToInt;
int main()
{
int testVariable = 8;
//This crashes on run time with Seg fault but no compilation error/warnings.
refToInt = testVariable;
return 0;
}
使用 GCC 版本 5.4.0 编译时
g++ -Wall referencesTest.cpp -o output
它在运行时因分段错误而崩溃,但为什么编译器没有在此处引发任何错误/警告? 我的理解是 C++ 中的引用总是需要在声明时进行初始化。 谁能帮忙解释一下为什么上面的代码编译器?
【问题讨论】: