问题
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();
}
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);
}
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 ?
回答1:
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 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.
This can be found in the draft C++ standard section 12.2 Temporary objects paragraph 5 which includes the following bullet
— A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.
回答2:
A temporary will be created and the reference is bound to that temporary (C++03 8.5.3.5). The temporary will be destroyed at the end of the constructor call, leaving a dangling reference. This is specified in C++03 12.2.5:
A temporary bound to a reference member in a constructor's ctor-initializer (12.6.2) persists until the constructor exits.
来源:https://stackoverflow.com/questions/21481481/initializing-reference-member-variable-with-literal