Non const lvalue references

后端 未结 2 821
时光说笑
时光说笑 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:58

    That is because a temporary can not bind to a non-const reference.

    double &m = a;
    

    a is of type int and is being converted to double. So a temporary is created. Same is the case for user-defined types as well.

    Foo &obj = Foo(); // You will see the same error message.
    

    But in Visual Studio, it works fine because of a compiler extension enabled by default. But GCC will complain.

提交回复
热议问题