lundi 18 mars 2019

forwarded argument is not moved. why?

in the following code the first call to logAndProcess picks the process function with const reference, the second one picks the process function with r-value reference. My question: shouldn't have the r-value function moved the argument string? Apparently it didn't. Why?

code:

#include <string>
#include <stdio.h>

void process(std::string && rvalue)
{
    std::string local = rvalue; // shouldn't rvalue have moved to local?

    printf("process &&rvalue. local: %s\n",local.c_str());
}


void process(const std::string & rvalue)
{
    printf("process const &rvalue\n");
}


template<class T>
void logAndProcess(T &&arg)
{
    printf("\nbefore process\n");
    process( std::forward<T>(arg) ); // picks the right overload of process one, depending on argument type.
    printf("after process\n");
}

main()
{
    //logAndProcess(std::string("aaa")); // called with rvalue - calls process(string &&)

    std::string tmp("tmp");
    logAndProcess(tmp); // calls process(const string &)

    printf("tmp not moved: %s\n", tmp.c_str());


    logAndProcess(std::move(tmp)); // calls process(string &&)

    printf("tmp moved?: %s\n not!", tmp.c_str());


    return 0;
}

output:

before process
process const &rvalue
after process
tmp not moved: tmp

before process
process &&rvalue. local: tmp
after process
tmp moved?: tmp

Aucun commentaire:

Enregistrer un commentaire