What kind of problems for not forwarding universal reference?

后端 未结 4 1834
清酒与你
清酒与你 2021-02-06 01:47

As far as I know, in C++11, universal reference should always be used with std::forward, but I am not sure of what kind of problem can occur if std::forward

4条回答
  •  悲哀的现实
    2021-02-06 02:09

    Let's say f is called like this:

    f(someType{});
    

    If the body of f performs some kind of operation on x

    foo(x);
    

    and there are two overloads for foo

    void foo(someType const&);
    
    void foo(someType&&);
    

    without using std::forward, as x is an lvalue the following overload is called

    void foo(someType const&);
    

    which might cost you a potential optimization.

    Using

    foo(std::forward(x));
    

    makes sure the correct overload of foo is selected.

提交回复
热议问题