What kind of problems for not forwarding universal reference?

后端 未结 4 1836
清酒与你
清酒与你 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:14

    Things with a name are lvalues. That means that in the function body, t is an lvalue. It doesn't matter if the universal reference ends up as an lvalue reference or as an rvalue reference. If it's named, it's an lvalue.

    If you thus pass that argument along directly, you will be passing an lvalue.

    In a situation where you want to just pass along an opaque argument to another function, you want to pass it exactly as-is. If it was an lvalue, you want to pass it as an lvalue; if it was an rvalue you want to pass an rvalue. As explained, passing it directly passes it as an lvalue always. forward does the magic needed to pass it as the right kind of value,

    Code that always passes an lvalue will likely suffer from a performance perspective but I would say that you can ignore that when thinking about this particular issue. There is a more pressing concern for not always passing an lvalue: while copying some types may be expensive, some other types cannot be copied at all, like std::unique_ptr. For those types preserving rvalueness when forwarding is not a matter of performance but of getting your code to even compile.

提交回复
热议问题