Assigning value to function returning reference

后端 未结 7 943
温柔的废话
温柔的废话 2020-12-19 07:53
#include
using namespace std;

int &fun()
{
  static int x = 10;
  return x;
}
int main()
{
   fun() = 30;
   cout << fun();
   return 0;
}         


        
7条回答
  •  -上瘾入骨i
    2020-12-19 08:11

    Returning a reference is quite useful.

    For example it's what std::map::operator[] does. And I hope you like the possibility of writing my_map[key] = new_value;.

    If a regular (non-operator) function returns a reference then it's ok to assign to it and I don't see any reason for which this should be forbidden.

    You can prevent assignment by returning a const X& or by returning X instead if you really want.

提交回复
热议问题