Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

references in c++ problem

Tags:

c++

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;
 }
like image 267
brett Avatar asked Aug 05 '10 06:08

brett


2 Answers

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 C++ destructor & function call order for a more detailed description of the order of destruction and the return statement.

like image 190
Saxon Druce Avatar answered Oct 17 '22 20:10

Saxon Druce


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.

like image 22
Michael Aaron Safyan Avatar answered Oct 17 '22 19:10

Michael Aaron Safyan