[英]Is there a shorthand for std::lock_guard<std::mutex> lock(m)?
Exactly what the question states.正是问题所述。 In C++, ideally 11, but curious about 14 and later too, is there a shorthand syntax for:
在 C++ 中,理想情况下为 11,但对 14 及更高版本也感到好奇,是否有以下简写语法:
std::mutex someMutex;
std::lock_guard<std::mutex> lg(someMutex);
Ideally something that infers the type of mutex to avoid the refactoring if I ever wanted to change to a std::recursive_mutex
.理想情况下,如果我想更改为
std::recursive_mutex
,可以推断互斥锁的类型以避免重构。
In other words, a way to do this:换句话说,有一种方法可以做到这一点:
std::mutex someMutex;
std::lock_guard lg(someMutex);
Or或者
auto lg = make_lock_guard(someMutex);
For all the type deduction powers of modern C++, it just seems awfully redundant to go typing std::lock_guard<std::mutex>
every time I want to make one.对于现代 C++ 的所有类型推导能力,每次我想要创建一个
std::lock_guard<std::mutex>
都显得非常多余。
For pre-C++17: 对于预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 the fact that copy-list-initialization doesn't create an additional temporary (even conceptually). 这利用了复制列表初始化不会创建额外临时(甚至概念上)的事实。 The one-parameter constructor is
explicit
and can't be used for copy-list-initialization, so we lock the mutex first and then use the std::adopt_lock
constructor. 单参数构造函数是
explicit
,不能用于复制列表初始化,因此我们首先锁定互斥锁,然后使用std::adopt_lock
构造函数。
The return value is then directly bound to lg
, which extends its lifetime to that of the reference, once again creating no temporary (even conceptually) in the process. 然后返回值直接绑定到
lg
,这会将其生命周期延长到引用的生命周期,再次在进程中不创建临时(甚至概念上)。
In addition to what @TC's answer hinted at, here's the C++17 way: 除了@ TC的回答所暗示的,这里是C ++ 17的方式:
auto lock = std::lock_guard(someMutex);
You can read about the changes in this proposal: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0091r3.html 您可以阅读此提案中的更改: http : //www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0091r3.html
Both current answers suggest using the auto keyword to avoid typing the type name. 目前的两个答案都建议使用auto关键字来避免输入类型名称。 It's not wrong but I prefer my code to contain the typename and so use the auto keyword very sparingly.
这没有错,但我更喜欢我的代码包含typename,因此非常谨慎地使用auto关键字。 I would advocate aliasing the type:
我会提倡别名类型:
using MutexLockGuard = std::lock_guard<std::mutex>;
For C++17 and newer use just:对于 C++17 和更新版本,只需使用:
std::lock_guard lock(mutex)
As template deduction will do its job for you.因为模板扣除将为您完成它的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.