c++ int &ref = ref;格式正确

mcvgt66p  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(96)

我已经了解到,计算未初始化的变量是未定义的行为。特别是,int i = i;是未定义的行为。我读过What's the behavior of an uninitialized variable used as its own initializer?
但是,使用引用变量来初始化自身也是未定义的行为吗?特别是,int &ref = ref;也是UB吗?

int &ref = ref; // Is this well-formed or ill-formed or UB

字符串
所有的编译器都对上面的程序执行compile(clang给出警告)。这是因为它是未定义的行为,所以任何事情都可以发生,还是程序是良构的?
另外,如果我给ref赋值,程序的行为会和以前的情况不同吗?

int &ref = ref;

int main()
{
    ref = 1; //does this change the behavior of the program from previous case
}


我注意到,对于第二个片段,我们得到了一个segfault。
我读过的一些参考文献是:
What's the behavior of an uninitialized variable used as its own initializer?
Why is initialization of a new variable by itself valid?

mitkmikd

mitkmikd1#

这不是一种明确的行为。
[dcl.ref]p5:
[...]引用应初始化为引用有效的对象或函数。
没有int对象可供引用。
也可以说引用在其生存期之外被使用。
[basic.life]:
1.引用的生存期从初始化完成时开始。引用的生存期结束时,就像它是一个需要存储的标量对象一样。
1.本文档中对象和引用的属性仅在给定对象或引用的生存期内适用。
因此,引用不能在自身初始化之前被“使用”来初始化自身,这就是Clang对此的抱怨(https://godbolt.org/z/Ea4qPoWbs):

note: use of reference outside its lifetime is not allowed in a constant expression
    2 |     int& ref = ref;
                       ^

字符串

相关问题