Forwarding of return values. Is std::forward is needed?

后端 未结 3 1421
予麋鹿
予麋鹿 2021-02-03 21:00

I am writing library which wraps a lot of functions and methods from other library. To avoid coping of return values I am applying std::forward like so:

         


        
3条回答
  •  再見小時候
    2021-02-03 21:55

    In the case that you do know that t will not be in a moved-from state after the call to f, your two somewhat sensible options are:

    • return std::forward(t) with type T&&, which avoids any construction but allows for writing e.g. auto&& ref = wrapper(42);, which leaves ref a dangling reference

    • return std::forward(t) with type T, which at worst requests a move construction when the parameter is an rvalue -- this avoids the above problem for prvalues but potentially steals from xvalues

    In all cases you need std::forward. Copy elision is not considered because t is always a reference.

提交回复
热议问题