Usage of std::forward vs std::move

前端 未结 3 1781
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 09:53

I always read that std::forward is only for use with template parameters. However, I was asking myself why. See the following example:

void Imag         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 10:16

    I recommend reading "Effective Modern C ++" by Scott Meyers, specifically:

    • Item 23: Understand std::move and std::forward.
    • Item 24: Distinguish universal references for rvalue references.

    From a purely technical perspective, the answer is yes: std::forward can do it all. std::move isn’t necessary. Of course, neither function is really necessary, because we could write casts everywhere, but I hope we agree that that would be, well, yucky. std::move’s attractions are convenience, reduced likelihood of error, and greater clarity.

    rvalue-reference

    This function accepts rvalues and cannot accept lvalues.

    void ImageView::setImage(Image&& image){
        _image = std::forward(image);        // error 
        _image = std::move(image);           // conventional
        _image = std::forward(image); // unconventional
    }
    

    Note first that std::move requires only a function argument, while std::forward requires both a function argument and a template type argument.

    Universal references (forwarding references)

    This function accepts all and does perfect forwarding.

    template  void ImageView::setImage(T&& image){
        _image = std::forward(image);
    }
    

提交回复
热议问题