Why int& a = is not allowed in C++?

前端 未结 3 2015
轻奢々
轻奢々 2021-01-18 05:47

I am reading about references in C++. It says that int& a = 5 gives compile time error.

In Thinking in C++ - Bruce Eckel, author says that

3条回答
  •  花落未央
    2021-01-18 06:04

    "The storage must be const because changing it would make no sense."

    If you want a be a reference to a const value, you must declare it as const, because a is referencing to a temporary constant value, and changing it is not possible.

    const int &a = 123;
    a = 1000; // `a` is referencing to temporary 123, it is not possible to change it
              // We can not change 123 to 1000
              // Infact, we can change a variable which its value is 123 to 1000
              // Here `a` is not a normal variable, it's a reference to a const
              // Generally, `int &a` can not bind to a temporary object
    

    For non-const bindings:

    int x = 1;
    int &a = x;
    

    a is a reference to a lvalue. Simple speaking, it's an alias name for another variable, so on the right hand you should give a variable. The reference a can not change and bind to another variable after it's first binding;

    In C++11, you can reference to temporary objects/values by rvalue references:

    int &&a = 123;
    

提交回复
热议问题