用文字初始化引用成员变量 [英] Initializing reference member variable with literal

查看:99
本文介绍了用文字初始化引用成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我正在用文字初始化引用变量.

In the following code , I am initializing a reference variable with a literal.

class ABC
{
  public:
     const int& a;
     ABC():a(43) { }
     void newfoo()
     {
           printf("NEWFOO %d",a);
     }
};
int main()
{
   ABC obj;
   obj.newfoo();
}

该程序的输出为NEWFOO 32767,当我知道以下代码可以正常工作时,这似乎是不合逻辑的.

The output of this program is NEWFOO 32767 which seems illogical when I know that the following code works just fine.

int main()
{ 
  const int& b=3;
  printf("%d",b);
}

这是怎么回事?如果编译器在初始化参考变量时声明了一些temp变量,那么该变量的范围不是在main内部,因为该类在全局范围内?

What is happening here ? If compiler declares some temp variable during initializing of the reference variable , then isn't the scope of that variable will be inside main since the class is in global scope ?

推荐答案

即使没有任何标志,clang也会对此代码产生以下警告(

Well clang produces the following warning for this code even without any flags (see it live):

warning: binding reference member 'a' to a temporary value [-Wdangling-field]
 ABC():a(43) { }
         ^~

另一方面,

gcc需要-Wall-Wextra.

gcc on the other hand requires either -Wall or -Wextra.

,如果我们查看此参考初始化参考,它会说:

and if we check out this reference initialization reference it says:

与构造函数初始化程序列表中引用成员的临时绑定仅在构造函数退出之前一直存在,而不是只要对象存在就保留.

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 临时对象段落 5 中找到,其中包括以下项目符号

This can be found in the draft C++ standard section 12.2 Temporary objects paragraph 5 which includes the following bullet

—在构造函数的ctor-initializer(12.6.2)中,临时绑定到引用成员的行为一直存在,直到构造函数退出.

— A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.

这篇关于用文字初始化引用成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆