1

When trying to understand the full meaning of condition variable wait_for:

bool wait_for (unique_lock<mutex>& lck, const chrono::duration<Rep,Period>& rel_time, Predicate pred);

It is explained in a few places as equivalent to wait_until with the following format:

wait_until (lck, chrono::steady_clock::now() + rel_time, std::move(pred));

instead of "pred" they put there "std::move(pred)", I was wondering how does this move changes the predicate or its evaluation and what is the difference between "pred" and "move::pred"

Thanks Shuki.

Arty
  • 14,883
  • 6
  • 36
  • 69
Shuki
  • 11
  • 4
  • std::move just moves (transfers ownership) of object instead of doing copy. If you call `wait_for(...pred)` then wait_for makes a copy of predicate functor. While std::move says that wait_for can transfer object and delete it after. – Arty Mar 02 '21 at 10:35
  • then why its not equivalent to wait_until (lck, chrono::steady_clock::now() + rel_time, pred) why its important to add std::move? – Shuki Mar 02 '21 at 11:09
  • It is totally equivalent, using or not using std::move makes only tiny difference on performance (speed and memory). Because without std::move it will copy `pred` object, and with it it will not copy but just move ownership. I think in your tutorial that you read they didn't mean that std::move is important, they just did one example (wait_for) without std::move, and another example (wait_until) with move, just to make two different examples, but not to stress the importance of moving `pred` object around. – Arty Mar 02 '21 at 11:57
  • It is even true for any function `f(...)`, there is no difference at all if you call function with `f(obj)` or with `f(std::move(obj))`, it is totally same. The only tiny difference is that if object is not copy-able (no copy constructor) then you have to use std::move, but only because of this object's specifics. For function `f()` itself there is no difference, it will not even notice if `obj` is moved or just passed around (copied). `std::move` in most cases is meant just for efficiency, to avoid doing extra copies. – Arty Mar 02 '21 at 12:04

0 Answers0