exactly question states. in c++, ideally 11, curious 14 , later too, there shorthand syntax for:
std::mutex somemutex; std::lock_guard<std::mutex> lg(somemutex); ideally infers type of mutex avoid refactoring if ever wanted change std::recursive_mutex.
in other words, way this:
std::mutex somemutex; std::lock_guard lg(somemutex); or
auto lg = make_lock_guard(somemutex); for type deduction powers of modern c++, seems awfully redundant go typing std::lock_guard<std::mutex> every time want make one.
for pre-c++17:
template<class mutex> std::lock_guard<mutex> make_lock_guard(mutex& mutex) { mutex.lock(); return { mutex, std::adopt_lock }; } use as:
std::mutex somemutex; auto&& lg = make_lock_guard(somemutex); this takes advantage of fact copy-list-initialization doesn't create additional temporary (even conceptually). one-parameter constructor explicit , can't used copy-list-initialization, lock mutex first , use std::adopt_lock constructor.
the return value directly bound lg, extends lifetime of reference, once again creating no temporary (even conceptually) in process.
Comments
Post a Comment