Can references refer to invalid location in C++?

 

 

  在C++中,引用比指针更加的安全,一方面是因为引用咋定义时必须进行初始化,另一方面是引用一旦被初始化就无法使其与其他对象相关联。

  但是,在使用引用的地方仍然会有一些例外。

  (1)Reference to value at uninitialized pointer

1 int *ptr;
2 int &ref = *ptr;  //Reference to value at some random memory location

  (2)Reference to a local variable is returned  

1 int& fun()
2 {
3      int a = 10;
4      return a;
5 }

  一旦fun()返回,fun()中分配在stack上的空间就会被回收。因此指向局部变量的引用是非法的。

  

 

 

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

 


  转载请注明:http://www.cnblogs.com/iloveyouforever/

   2013-11-25  21:28:30

 

posted @ 2013-11-25 21:29  虔诚的学习者  阅读(253)  评论(0编辑  收藏  举报