Should I return an rvalue reference parameter by rvalue reference?

前端 未结 4 1753
礼貌的吻别
礼貌的吻别 2020-12-12 22:51

I have a function which modifies std::string& lvalue references in-place, returning a reference to the input parameter:

std::string& tra         


        
4条回答
  •  时光说笑
    2020-12-12 23:31

    Some (non-representative) runtimes for the above versions of transform:

    run on coliru

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    double GetTicks()
    {
        struct timeval tv;
        if(!gettimeofday (&tv, NULL))
            return (tv.tv_sec*1000 + tv.tv_usec/1000);
        else
            return -1;
    }
    
    std::string& transform(std::string& input)
    {
        // transform the input string
        // e.g toggle first character
        if(!input.empty())
        {
            if(input[0]=='A')
                input[0] = 'B';
            else
                input[0] = 'A';
        }
        return input;
    }
    
    std::string&& transformA(std::string&& input)
    {
        return std::move(transform(input));
    }
    
    std::string transformB(std::string&& input)
    {
        return transform(input); // calls the lvalue reference version
    }
    
    std::string transformC(std::string&& input)
    {
        return std::move( transform( input ) ); // calls the lvalue reference version
    }
    
    
    string getSomeString()
    {
        return string("ABC");
    }
    
    int main()
    {
        const int MAX_LOOPS = 5000000;
    
        {
            double start = GetTicks();
            for(int i=0; i

    output

    g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
    
    Runtime transformA: 444 ms
    Runtime transformB: 796 ms
    Runtime transformC: 434 ms
    

提交回复
热议问题