1

Can you tell me why output of that reference member of class different in different compilers?

  class B
  {
     int& aRef;
     public:
     B(int c):aRef(c){}

     void Print()
     {
         cout<<aRef<<endl;
     }
  };

  void f(int s)
  {
    int& lcRef=s;
    cout<<lcRef<<endl;
  }

 int main()
 {
    int x=100;
    B s(x);
    s.Print(); //ms c++ output : 3323244, gcc output :100
    f(x);   //ms c++ output : 100, gcc output:100
    return 0;
 }


And second question parameter of function f(int s) behaves same logic as contructor of class B's initialization?

4

3 回答 3

5
B(int c):aRef(c){}

This binds the reference to the constructor argument c. Since it's passed by value, it's destroyed when the constructor returns, leaving the reference dangling. Accessing it after the constructor returns gives undefined behaviour; in this case, it tries to access a lump of deallocated stack memory which may or may not still be accessible, and may or may not still contain the old value.

You want to pass by reference, to bind to the caller's variable:

B(int& c) : aRef(c) {}
于 2013-11-02T13:09:33.827 回答
4

f function is correct and works as expected but here:

B(int c):aRef(c){}

You are basically assigning to int& aRef the address to a local automatic allocated variable (c). Now, references are safer than pointers but assigning a automatic allocated variable which goes out of scopes is one of the few cases that invalidates them.

The fact that the output is correct on GCC doesn't imply anything since that variable is not valid anymore ouside the constructor.

于 2013-11-02T13:06:26.913 回答
2

The difference is that within f, you are taking the reference to a parameter. This parameter is still valid when you print the content through the reference. For the constructor of B, you are storing the reference and when the constructor finishes, the referenced object goes out of scope, hence the reference becomes a dangling reference and using it becomes invalid. The output from GCC is just a coincidence, but it is not guaranteed.

于 2013-11-02T13:08:27.313 回答