lvalue binding to rvalue reference

后端 未结 2 1911
青春惊慌失措
青春惊慌失措 2020-12-20 19:57

I am trying to understand how lvalues bind to rvalue references. Consider this code:

#include 

template
void f(T&&         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 20:39

    0x499602D2 has already answered your question; nevertheless, the following changes to your code might give further insights.

    I have added a static_assert to f to check the deduced type:

    #include 
    
    template
    void f(T&& x) {
        static_assert(std::is_same::value,"");
        std::cout << x;
    }
    

    The assert does not fail, so the type of x in f is eventually int& (in this particular example).

    I have changed how g is called in main:

    g(std::move(x));
    

    Now the code compiles and the program works as expected and prints 44.

    Hope this helps a bit in understanding rvalue references.

提交回复
热议问题