Ziz*_*Tai 5 c++ templates c++11
std::for_each 按值接受并返回仿函数:
template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );
Run Code Online (Sandbox Code Playgroud)
虽然仿函数可以移入和移出,但我很感兴趣是否根本不涉及对象构造.如果我这样声明我自己my_for_each:
template< class InputIt, class UnaryFunction >
UnaryFunction&& my_for_each( InputIt first, InputIt last, UnaryFunction&& f);
Run Code Online (Sandbox Code Playgroud)
在里面my_for_each,打电话f给std::forward<UnaryFunction>(f)(...),我可以避免移动构造参数的成本,并作为奖励能够尊重ref-qualifiers.但我不确定应该归还什么.如果我做:
return std::forward<UnaryFunction>(f);
Run Code Online (Sandbox Code Playgroud)
可以发生坏事(例如,悬空引用)吗?
正如另一个正确答案所指出的那样,传递const&和右值参考参数是危险的,因为参考寿命延长不会通勤.
当你想通过转发引用时返回正确的东西T&&是T.这会将右值变为临时值,并将左值作为引用.
所以:
template< class InputIt, class UnaryFunction >
UnaryFunction my_for_each( InputIt first, InputIt last, UnaryFunction&& f);
Run Code Online (Sandbox Code Playgroud)
哪个用于临时f创建(移动到)副本.
如果您存储此副本,它将被省略到存储,因此零额外费用.除非您不存储它,并且移动费用昂贵,否则这基本上是最佳的.