我了解到评估未初始化的变量是未定义的行为。特别int i = i;是未定义的行为。我已阅读未初始化变量用作其自身初始化程序的行为是什么?
但是,使用引用变量来初始化自身也是未定义的行为吗?特别是,int &ref = ref;根据 C++ 标准,UB 也是吗?
int &ref = ref; // Is this well-formed or ill-formed or UB
Run Code Online (Sandbox Code Playgroud)
所有编译器都会编译上述程序(clang 会发出警告)。这是因为它是未定义的行为,所以任何事情都可以发生,还是程序格式良好?
此外,如果我为 分配一些值ref,程序的行为会与之前的情况相比发生变化吗?
int &ref = ref;
int main()
{
ref = 1; //does this change the behavior of the program from previous case
}
Run Code Online (Sandbox Code Playgroud)
我注意到对于第二个片段,我们遇到了段错误。
我读过的一些参考文献是:
为什么初始化std::stringto ""(通过 lambda)会崩溃?
这不会崩溃:
static std::string strTest2 =
[](){std::string * s = &strTest2; (*s) = "a"; return s->c_str();}();`
Run Code Online (Sandbox Code Playgroud)
这个技巧(首先将其初始化为非空,但预期的最终值为空)不会崩溃:
static std::string strTest3 =
[](){std::string * s = &strTest3; (*s) = "b"; (*s) = ""; return s->c_str();}();
Run Code Online (Sandbox Code Playgroud)
在这里崩溃了(*s) = ""。是因为它是空字符串吗?很特别吗?std::string分配给 时是否未构造/初始化""?
static std::string strTest1 =
[](){std::string * s = &strTest1; (*s) = ""; return s->c_str();}();`
Run Code Online (Sandbox Code Playgroud)