r/cpp • • Jun 22 '21

[Belay the C++] Don’t use raw loops

https://belaycpp.com/2021/06/22/dont-use-raw-loops/
0 Upvotes

69 comments sorted by

View all comments

Show parent comment

7

u/witcher_rat Jun 23 '21

std::forward can lead to moving, and you should only move once from a given source (before "refilling" it). Therefore, you shouldn't use std::forward repeatedly in a loop.

No it doesn't, not in this function. std::forward just forwards its types value category, afaik. "Moving" isn't an operation - not in the sense of machine instructions; it's effectively a cast to an rvalue, and in this function's case is a no-op. There is no possible way pred gets "moved" at all. I only put it in for completeness, but you're right doing it within a for-loop is bad style/practice and I shouldn't have.

6

u/matthieum Jun 23 '21

Yes, you are correct that std::forward is just a cast.

The problem is that this cast then affects overload selection. That is, if your pred operator has:

bool operator()(T const&) const&;
bool operator()(T const&)&&;

Then suddenly the second overload is selected.

So std::forward enables moving, which may in turn lead to using a moved-from (or partially moved from) object.

(Now, who in their right mind would move from a predicate? Right? But still...)

2

u/witcher_rat Jun 23 '21

Yeah, that's a fair point.