References in a C ++ Problem

I heard that C ++ links can only be initialized once, but this gives me 1 - this is my conclusion and does not return any errors!

 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
source share
3 answers

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

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

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

See the C ++ destructor and function call order for a more detailed description of the kill order and the return statement.

+9
source

; . h , j ( ). j, h, h .

+5

, , , , , ( ), .

0

All Articles