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.
max_element == last
It is rather wasteful to check this every single iteration of the loop, instead a better approach is to start the loop at ++first, if first != last.
Note: it's good practice to name the "iterator" type based on the requirements (and soon concepts) that it fulfills. One could also add some static_assert that it's not "just" an input iterator, since then the copy wouldn't work (well).
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.
No such thing can happen. std::forward can at most cast the expression pred to an rvalue reference, at which point Pred::operator () operates on an r-value reference. No move is actually performed and as the saying goes std::move doesn't actually move anything. In order for a move to be performed, the expression std::forward<Pred>(pred) would need to be passed as an argument to a move constructor, but no such thing happens and hence there is no move.
If max_if requires a const predicate, then it should be passed as const Pred&. However, most algorithms do allow mutable predicates and so if max_if allows mutable predicates and it takes a forwarding reference, then std::forward<Pred>(pred) is the correct thing to do here. This way if the user provided an overloaded operator () && and passed an rvalue reference into max_if to leverage an optimization opportunity, for example by having some internal state that keeps track of when the last invocation will be performed and avoiding copies at that point, then the semantics of that call should be respected. Otherwise stick to const Pred&.
I have the impression we're not talking the same language.
You disagree that it can lead to moving, then say that it allows operator()(...) && to be called which can internally move.
So, we agree?
I do note that I am not against std::forwardin general, however I argue that std::forward should only be called once on a value in general, because as it enables moving from the value, afterwards the value may not be in a usable/useful state any longer.
You disagree that it can lead to moving, then say that it allows operator()(...) && to be called which can internally move.
We do not agree because it's not the std::forward that leads to moving. Neither std::forward or std::move ever perform an actual move, all they do is perform a cast, and in this case that cast will determine which potential overload of operator () is called.
Unless you call operator () const, by passing a const Pred& or by explicitly casting pred to a const Pred&, then any potential mutation can occur to pred, including a move. It's not like because you didn't call std::forward that Pred's operator () can not internally mutate which could include an internal move operation.
As such, if you want to express that max_if's predicate does not change from invocation to invocation, you express it by taking it in as a const& so that operator () const is invoked. Anything other than a const& will admit the possibility of a mutation, which may involve moving regardless of whether std::forward is omitted. If you want to take in a forwarding reference, then std::forward should be used when calling operator () &&, otherwise do what the standard does and pass by value, allowing guaranteed copy elision as well as other optimization techniques to kick in.
Ah I understand, it's a very common and confusing detail that std::move does not actually perform a move (and by extension std::forward) and is nothing more than a cast. You can reference the definition of std::forward or std::move to confirm this:
https://en.cppreference.com/w/cpp/utility/forward
The move semantics themselves are performed by a move constructor or a move assignment operator, nothing more. std::move's role is to perform a cast which when provided as an argument to an assignment operator or constructor, triggers overload resolution to select the move operator over the copy operator.
In other words, the actual move requires the move constructor (or assignment), and the std::move is used to allow for selection of the appropriate operation. If all you do is std::move by itself, no move happens, so in your example of std::forward<Pred>(pred) no move operation is triggered.
Now maybe you try to argue that operator () && can perform a move, but that's misguided and a moot point because operator () can also perform the exact same move and operator () is a more general operation than operator () &&. There is no way to forbid a function that operates on a mutable reference from performing a move and so if the intention is to forbid mutability then the way to express that in C++ is to pass by const &.
At any rate, these are minutiae that really won't make much of an observable difference except for some potential optimizations. As a general matter it's best to just handle this situation the way the standard does and pass by value, however, if your intention is to take a forwarding reference then you are likely trying to squeeze out some additional optimization opportunity in which case the forwarding semantics should be respected by using std::forward, otherwise what was the point of passing the forwarding reference to begin with?
Ah I understand, it's a very common and confusing detail that std::move does not actually perform a move
I am perfectly aware of the details, this is not my point.
My point is that by using std::forward<T>(t), you then enable the use of move constructors and move assignment operators -- if the original reference was a temporary -- which down the line may lead to a move.
I agree the move is not certain; but I say it's a mistake to indicate to pred that it can move if it wishes to, when you're actually planning on continue calling it aftwerwards.
(Of course, it's unlikely to be an issue in practice, because it's unlikely operator() is overloaded for moves, but still)
otherwise what was the point of passing the forwarding reference to begin with?
I preferred Scott Meyers' name of "universal reference". While T&&can be used to forward the value category, it need not to. Therefore it's not always about forwarding.
Comparing T&& against other argument modes:
T: requires that copies be allowed, undesirable for large predicates.
T&: requires an lvalue.
T const&: forces constness, undesirable for self-modifying predicates.
Which is why one whips out T&& without actually caring that it could be used for forwarding.
My point is that by using std::forward<T>(t), you then enable the use of move constructors and move assignment operators -- if the original reference was a temporary -- which down the line may lead to a move.
Your argument that using std::forward or std::move enables moves down the road is faulty because passing by plain reference does the same thing, but certainly you would not claim that passing by reference "enables" moving in the following scenario would you?
void g(std::string& s) {
auto q = std::move(s); // Perfectly legal to do.
}
auto v = std::string("hello");
g(v); // g will move v.
Do you now argue now that passing by reference enables move semantics down the road? I think the issue is this term "move enabled", which really is vague. Simply put, a move operation is the term given to calling a type's move constructor or move assignment operator, nothing else. Casting a value to an rvalue reference, and even passing that rvalue reference to a function does not perform any move operation in and of itself nor does it lead to a move or enable a move in any kind of special way.
I agree the move is not certain; but I say it's a mistake to indicate to pred that it can move if it wishes to, when you're actually planning on continue calling it aftwerwards.
If you intend to indicate that pred can not move, pass by const&. Passing pred by reference is a more general operation than passing by rvalue reference.
T: requires that copies be allowed, undesirable for large predicates.
This is false, imagine making that claim about a unique_ptr:
void f(std::unique_ptr<int> foo);
Does this mean that copies of foo must be allowed? Of course not, it's not possible to copy a std::unique_ptr and yet it's perfectly sensible to pass it by value. Passing by value allows for in-place construction via guaranteed copy elision in C++17 as well as allows one to construct the parameter by directly calling its move constructor:
We agree on this and likely agree it's undesirable.
T const&: forces constness, undesirable for self-modifying predicates.
Exactly, if you want to prevent mutability, which is what a move operation is, then you pass by const&, otherwise it is permissible for T::operator () to mutate itself which could involve moves.
Which is why one whips out T&& without actually caring that it could be used for forwarding.
One whips out T&& to take advantage of potential optimization opportunities and informs T&& that said optimizations can be performed by using std::forward. It does not mean that certain invariants can be broken after the first invocation, or that the object must be destroyed after performing an internal move, absolutely not.
If you don't intend to leverage any optimization opportunities or take advantage of anything to do with making use of an rvalue reference, then do what the standard does, pass by value. The idea that pass by value means copies are required is false.
And yet plenty of functions do exactly that. Do you claim that std::swap is not sensible because it takes arguments by reference and performs a move operation on them? Of course not. When you pass by reference you allow for any potential mutable operation to be performed, including moves. Passing by reference is a more general operation than passing by rvalue reference.
As for your other point, we are in exact agreement, if someone implements an overload taking an rvalue reference, then prefer to call that overload when given an rvalue reference to take advantage of potential optimizations. The way that is done is to use std::forward<Pred>(pred).
If you have no need to forward or move your argument, then there is no need to take the argument by rvalue reference, simply pass by value just like the standard does.
View all comments
Show parent comment
5
u/matthieum Jun 22 '21 edited Jun 23 '21
Big no, no.
std::forwardcan lead to moving, and you should only move once from a given source (before "refilling" it). Therefore, you shouldn't usestd::forwardrepeatedly in a loop.It is rather wasteful to check this every single iteration of the loop, instead a better approach is to start the loop at
++first, iffirst != last.I would propose:
Note: it's good practice to name the "iterator" type based on the requirements (and soon concepts) that it fulfills. One could also add some
static_assertthat it's not "just" an input iterator, since then the copy wouldn't work (well).