c ++问题中的引用

bre*_*ett 5 c++

我听说c ++中的引用只能被初始化一次,但是这给了我1是我的输出而没有返回任何错误!

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

   ~f() { 
     h = 2; 
   } 

   int& h; 
 };

 int i() { 
   int j = 3; 
   f k(j); 
   return j;
 }
Run Code Online (Sandbox Code Playgroud)

Sax*_*uce 9

在捕获返回值j之后调用f的析构函数.

如果你希望j为2,你可能想要这样的东西:

int i( )  
{  
    int j=3;  
    {
        f k(j);  
    }
    return j; 
}
Run Code Online (Sandbox Code Playgroud)

有关销毁顺序和return语句的更详细说明,请参阅C++析构函数和函数调用顺序.


Mic*_*yan 5

您仍在初始化参考一次; 赋值和初始化是不一样的.初始化设置h为引用j(您永远不会更改).您的赋值仅仅更改其值j相同h,但不会导致h引用其他变量.