[英]Move an element from std::deque in C++11
我们知道std::deque::front()
返回对deque的第一个元素的引用。 我想知道这段代码是否总是安全的:
//deque of lambdas
deque<function<void(void)>> funs;
// then is some other place:
// take a lock
m.lock();
auto f = move(funs.front()); // move the first lambda in f
funs.pop_front(); // remove the element from deque //now the value is hold by f
m_.unlock(); // unlock the resorce
f(); //execute f
我已经尝试使用gcc-4.9这个代码并且有效,但我不知道我们是否可以认为这个代码是安全的!
std::function
move构造std::function
不保证不会抛出异常,因此您有一个异常安全问题。 由于您没有对m
使用RAII锁,因此如果auto f = move(funs.front());
,它将保持锁定状态auto f = move(funs.front());
抛出。 您可以使用std::unique_lock
更正问题:
std::unique_lock<decltype(m)> lock{m};
if (!funs.empty()) {
auto f = move(funs.front()); // move the first lambda in f
funs.pop_front(); // remove the element from deque //now the value is hold by f
lock.unlock(); // unlock the resorce
f(); //execute f
}
或者std::lock_guard
:
function<void()> f;
{
std::lock_guard<decltype(m)> lock{m};
if (!funs.empty()) {
f = move(funs.front()); // move the first lambda in f
funs.pop_front(); // remove the element from deque //now the value is hold by f
}
}
if (f) f(); //execute f
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.