c++ - 用文字初始化引用成员变量

标签 c++ variables reference initialization

在下面的代码中,我用文字初始化了一个引用变量。

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/

相关文章:

c++ - 如何使用Google Protobuf实现Map结构

c++ - shader.hlsl 文件导致错误?

c++ - 有没有办法在 C/C++ 中撤消 SQLite3 步骤调用?

php - 使用 $_POST 变量时 MySQL 查询不工作

c++ - 程序运行时如何创建新变量或对象? (C++)

c++ - 有没有办法拥有更严格的泛型仿函数参数?

mysql - 游标上的存储过程变量赋值

c++ - 如何在 C++ 中使不明确的调用不同?

C++ 使用和返回引用

reference - 如何制作引用文献的副本? (生活问题)