Non const lvalue references

后端 未结 2 820
时光说笑
时光说笑 2020-12-07 15:41

Why can you do this

int a;
const double &m = a;

But when you do this

int a;
double &m = a;

you ge

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 15:59

    Because making modification on a temporary is meaningless, c++ don't want you to bind non-const reference to a temporary. For example.

    int a;
    double &m = a;  // caution:this does not work.
    

    What if it works? a is of type int and is being converted to double. So a temporary is created.

    You can modify m, which is bound to a temporary, but almost nothing happens.After the modification, variable a does not change(what's worse, you might think a has changed, which may cause problems).

提交回复
热议问题