use of rvalue reference and auto

前端 未结 4 1578
孤城傲影
孤城傲影 2021-01-19 21:11

Given the code below, everything works. How come that the variable d is reference to int? What is going on?

int main()
{
    int a= 10;
    int &&b =         


        
相关标签:
4条回答
  • 2021-01-19 21:30

    Worth mentioning on top of the reference collapsing rules is how to force d to be an rvalue reference. You can use std::move for this:

    int a =4; 
    auto &&d = std::move(a); // d is type &&
    

    Of course when talking integers, rvalue references are silly, as pass by value is just as efficient. This is useful in forcing move semantic optimizations, say if you wanted to insert a complex type at the end of a function, where that type would go out of scope...

    vector<std::string> v;
    void f()
    {
        string s;
        foo(s); // do some kind of operation on s.
        v.push_back(std::move(s)); // use push_back( &&) instead of push_back(const &); 
    }
    
    0 讨论(0)
  • 2021-01-19 21:31

    auto&& invokes perfect forwarding. As a is an lvalue of type int, d is an lvalue reference to int.

    0 讨论(0)
  • 2021-01-19 21:35

    There is a special rule in type deduction. In auto &&d = a; "auto&&" is an rvalue reference to a non-const non-volatile type and "a" is an lvalue, then this special rule is applied: the type of "a" is treated as int& instead of int. Then as usual choose the type of "auto" to be identical to the type of "a", that is int&. So the type of "auto&&" is int& according to reference collapsing as mentioned by bames53.

    0 讨论(0)
  • 2021-01-19 21:43

    This has to do with the reference collapsing rules in type deduction.

    A& & becomes A&
    A& && becomes A&
    A&& & becomes A&
    A&& && becomes A&&
    
    0 讨论(0)
提交回复
热议问题