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

前端 未结 3 2050
轻奢々
轻奢々 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条回答
  •  猫巷女王i
    2021-01-18 05:53

    int& a = 5;
    

    In order for the above code to work, int& needs to bind to a temporary object of type int created out of the expression 5. But binding int& to a temporay didn't appeal to Bjarne Stroustrup — and he gave an example, similar to the following, to illustrate his point:

    void f(int &i) { ++i; }
    
    float x = 10.0;
    f(x); 
    std::cout << x <<< std::endl;
    

    What will the std::cout print1? Looks like it will print 11.

    It feels, ++i is changing the argument x, but it doesn't. This is one reason why the creator of C++ didn't permit temporaries to bind to non-const reference.

    However, you can do this:

    int const & i = 10;
    int const & j = x; //x is float
    

    And since C++11, you can do this:

    int && i = 10;
    int && i = x; //x is float
    

    Hope that helps.


    1. assuming int& can bind to the temporary created out of x.

提交回复
热议问题