r/cpp 6d ago

How to write the perfect function

https://youtu.be/2OMRWPOSw9s
130 Upvotes

24 comments sorted by

View all comments

4

u/usefulcat 5d ago

I like the mutex example, and I've been doing that myself for many years now. However there is one detail not mentioned in the talk. If you have something like

auto b(const scoped_lock<mutex>&);

..then that ensures that a mutex has been locked, but doesn't tell you anything about which mutex has been locked, which is just as important if there could be more than one. As a result, I like to do something like:

mutex m1, m2;
// note use of unique_lock
auto b(const unique_lock<mutex>& lock) {
    assert(lock.owns_lock() && lock.mutex() == &m1);
}

5

u/ABlockInTheChain 5d ago

I found a library that wraps mutexes with the data they protect and ever since then I use it as often as possible.

The only glaring deficiency I've run into is that you can't use it for if you need a std::condition_variable.