简体   繁体   English

c ++问题中的引用

[英]references in c++ problem

I heard references in c++ can be intitalized only once but this is giving me 1 is my output and not returning any error! 我听说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;
 }

The destructor of f is called after the return value j is captured. 在捕获返回值j之后调用f的析构函数。

You might want something like this, if you wanted j to be 2: 如果你希望j为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. 有关销毁顺序和return语句的更详细说明,请参阅C ++析构函数和函数调用顺序

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). 初始化设置h以便它引用j (你永远不会改变)。 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. 您的赋值仅更改j的值,该值与h相同,但不会导致h引用其他变量。

我希望这段代码只是为了显示问题,存储对类外定义的变量的引用是非常危险的,因为当引用的变量超出范围时,您的类没有任何控制(或知道)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM