在下面的代码中,我用文字初始化了一个引用变量。
class ABC
{
public:
const int& a;
ABC():a(43) { }
void newfoo()
{
printf("NEWFOO %d",a);
}
};
int main()
{
ABC obj;
obj.newfoo();
}
这个程序的输出是 NEWFOO 32767
,当我知道下面的代码可以正常工作时,这似乎不合逻辑。
int main()
{
const int& b=3;
printf("%d",b);
}
这里发生了什么?如果编译器在初始化引用变量期间声明了一些临时变量,那么该变量的范围是否会在 main 内部,因为该类在全局范围内?
最佳答案
即使没有任何标志,clang
也会为此代码生成以下警告 ( see it live ):
warning: binding reference member 'a' to a temporary value [-Wdangling-field]
ABC():a(43) { }
^~
gcc
另一方面需要 -Wall
或 -Wextra
。
如果我们查看 this reference initialization reference它说:
a temporary bound to a reference member in a constructor initializer list persists only until the constructor exits, not as long as the object exists.
这可以在草案 C++ 标准部分 12.2
Temporary objects 段落 5 中找到,其中包括以下项目符号
— A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.
关于c++ - 用文字初始化引用成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21481481/