lundi 19 février 2018

Confusion between std::move and std::forward

So I was just writing a sample and contrived example of std::forward for my understanding, but it didn't work the way I expected. In the program below

template<typename T>
void funcB(T&& obj)  // universal reference
{
    std::string local = std::move(obj.m_);   // using std::move on universal reference. Bad.
    std::cout << "funcB : " << local << '\n';
}

template<typename T>
void funcC(T&& obj)  // universal reference
{
    std::string local = std::forward<std::string>(obj.m_);   // using std::move on universal reference
    std::cout << "funcC : " << local << '\n';
}

int main()
{
    A obj("firstString");

   //funcA(obj);  // We get compiler error. Rvalue reference cannot be bound to Lvalue
    funcB(obj);  
    std::cout << "Main : " <<  obj.m_ << '\n';

    A obj2("secondString");
    funcC(obj2);
    std::cout << "Main : " << obj2.m_ << '\n';
}

In the output

funcB : firstString
Main : 
funcC : secondString
Main : 

In funcC, even though I have used universal references and here it is bound to Lvalue, the string is moved when I do std::forward. Hence the in the last line, after "Main:" there is no output. Can someone please how the string is moved even though obj is bound to Lvalue.

Aucun commentaire:

Enregistrer un commentaire