tags:

views:

143

answers:

3

Hi, I heard references in c++ can be intitalized only once but this is giving me 1 is my output and not returning any error!

 struct f { 
   f(int& g) : h(g) { 
     h = 1; 
   }

   ~f() { 
     h = 2; 
   } 

   int& h; 
 };

 int i() { 
   int j = 3; 
   f k(j); 
   return j;
 }
+5  A: 

You are still initializing the reference only once; assignment and initialization are not the same. The initialization sets up h so that it references j (which you never change). Your assignment merely changes the value of j which is the same as h, but does not cause h to refer to a different variable.

Michael Aaron Safyan
great. Thank you very much.
brett
+9  A: 

The destructor of f is called after the return value j is captured.

You might want something like this, if you wanted j to be 2:

int i( )  
{  
    int j=3;  
    {
        f k(j);  
    }
    return j; 
}

See http://stackoverflow.com/questions/2196327/c-destructor-function-call-order for a more detailed description of the order of destruction and the return statement.

Saxon Druce
A: 

I hope this code is only to display the issue, storing a reference to a variable defined outside of the class is very dangerous as your class doesn't have any control over (or knowlege of) when the referenced variable goes out of scope.

DevinEllingson