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>
There is no such rule to always use std::forward
with universal references. On the contrary, it can be dangerous to use std::forward
all over the place in functions with universal references. Take a look at the following example:
template
auto make_pair(T&& t)
{
return std::make_tuple(std::forward(t), std::forward(t)); // BAD
}
If you call this function with make_pair(std::string{"foobar"})
, the result is counter-intuitive, because you move from the same object twice.
Update: Here is another example to show, that it really makes sense to use universal references without perfect forwarding:
template
void foreach(Range&& range, Action&& action)
{
using std::begin;
using std::end;
for (auto p = begin(range), q = end(range); p != q; ++p) {
action(*p);
}
}
std::forward
for range or for action.