What are the main purposes of using std::forward and which problems it solves?

后端 未结 6 2164
执念已碎
执念已碎 2020-11-21 07:12

In perfect forwarding, std::forward is used to convert the named rvalue references t1 and t2 to unnamed rvalue references. What is the

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-21 07:48

    I think to have a conceptual code implementing std::forward can add to the discussion. This is a slide from Scott Meyers talk An Effective C++11/14 Sampler

    conceptual code implementing std::forward

    Function move in the code is std::move. There is a (working) implementation for it earlier in that talk. I found actual implementation of std::forward in libstdc++, in file move.h, but it is not at all instructive.

    From a user's perspective, the meaning of it is that std::forward is a conditional cast to an rvalue. It can be useful if I am writing a function which expects either an lvalue or rvalue in a parameter and wants to pass it to another function as an rvalue only if it was passed in as an rvalue. If I did not wrap the parameter in std::forward, it would be always passed as a normal reference.

    #include 
    #include 
    #include 
    
    void overloaded_function(std::string& param) {
      std::cout << "std::string& version" << std::endl;
    }
    void overloaded_function(std::string&& param) {
      std::cout << "std::string&& version" << std::endl;
    }
    
    template
    void pass_through(T&& param) {
      overloaded_function(std::forward(param));
    }
    
    int main() {
      std::string pes;
      pass_through(pes);
      pass_through(std::move(pes));
    }
    

    Sure enough, it prints

    std::string& version
    std::string&& version
    

    The code is based on an example from the previously mentioned talk. Slide 10, at about 15:00 from the start.

提交回复
热议问题