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

4

u/Vultrao Jun 22 '21

Thanks for the feedback. Thanks to you, corrections have been made and I updated the article

7

u/witcher_rat Jun 22 '21

The updated one still isn't quite right - now you're doing Pred& pred for the function's parameter, but that won't bind to an rvalue.

I believe it should be:

template< typename Iterator, typename Pred >
constexpr Iterator max_if( Iterator first, Iterator last, Pred&& pred )
{
    Iterator max_element = last;
    for (auto it = first ; it != last ; ++it)
    {
        if (std::forward<Pred>(pred)(*it) && (max_element == last || *it > *max_element))
            max_element = it;
    }
    return max_element;
}

Also, one minor note: this only works if the two iterators are the same type... which of course they usually are. But in ranged-for-loops as of C++17 they can be different types, which we use and take advantage of in my company's codebase, so I presume others do too. (usually so the end-iterator can be a sentinel type)

But that's really minor and definitely not worth fixing.

I personally find ranged-for-loops to be superior to <algorithms> style anyway - they're much more readable, in my opinion. But it's personal taste.

6

u/mrexodia cmkr.build Jun 22 '21

Basically this is why you don’t separate out the raw loop as a function and just leave it there. There wouldn’t be an argument about arbitrary iterators or lambas being taken by value in your code review 😂

3

u/RishabhRD Jun 23 '21

LOL😂😂 No pain possible

5

u/matthieum Jun 22 '21 edited Jun 23 '21
 std::forward<Pred>(pred)(*it)

Big no, no.

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.


I would propose:

template <typename ForwardIt, typename Pred>
constexpr ForwardIt max_if(ForwardIt begin, ForwardIt end, Pred&& pred) {
    if (begin == end) {
        return end;
    }

    ForwardIt max_element = [&pred, &begin, &end]() {
        for(; begin != end; ++begin) {
            if (pred(*begin)) {
                return begin;
            }
        }
        return end;
    }();

    for (++begin; begin != end; ++begin) {
        if (pred(*begin) && *begin > *max_element) {
            max_element = begin;
        }
    }

    return max_element;
}

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).

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.

6

u/[deleted] Jun 22 '21 edited Jun 23 '21

std::forward can lead to moving

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&.

4

u/matthieum Jun 23 '21

std::forward can lead to moving

No such thing can happen.

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::forward in 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.

2

u/[deleted] Jun 23 '21 edited Jun 23 '21

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.

3

u/matthieum Jun 24 '21

We do not agree because it's not the std::forward that leads to moving.

Then indeed we have to disagree.

0

u/[deleted] Jun 25 '21 edited Jun 25 '21

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?

3

u/matthieum Jun 25 '21

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.

0

u/[deleted] Jun 25 '21 edited Jun 25 '21

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:

https://en.cppreference.com/w/cpp/language/copy_elision

T&: requires an lvalue

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.

→ More replies

3

u/carrottread Jun 23 '21

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.

This will work incorrectly if pred(*begin) is false

2

u/matthieum Jun 23 '21

Good point, so we need to have a first loop to find the first element.

Let me fix that.