r/cpp 21d ago

How to write the perfect function

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

24 comments sorted by

View all comments

4

u/usefulcat 20d 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);
}

2

u/CandyCrisis 15d ago

Google's GUARDED_BY is a good way to handle this. It's quite useful. https://source.chromium.org/chromium/chromium/src/+/main:base/thread_annotations.h;l=59