Dangerous operation: functions that return references in C++

Functions that return references in C++

#include <iostream>  
using namespace std;  
  
int &fun()  
{  
    int x = 10;  
    return x;  
}  
  
int main()  
{  
    fun() = 30;  
    cout << fun();  
    return 0;  
}  

 

This program is very dangerous, why?

Because the fun function returns a reference to x, this is not wrong. We want to modify the value of x through fun()=30. We originally thought that the output of cout<<fun() should be 30, but we were wrong, cout< <fun() returns 10. The reason for this is that we did not consider that x is a local variable with the scope of the fun() function, and the returned x is a temporary variable. When we call fun()=30, we do change the value of the temporary variable to Up to 30. However, after the temporary variable is assigned, it will automatically end its own life with the end of the fun() function call.

What we see cout<<fun() just returns the value of x in the fun() function called at this time.

Guess you like

Origin blog.csdn.net/weixin_45590473/article/details/108684705