在c++ 11中从std::deque中移动一个元素

Move an element from std::deque in C++11

本文关键字:元素 一个 移动 c++ 中从 std deque      更新时间:2023-10-16

我们知道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构造函数不能保证不抛出异常,所以你有一个异常安全问题。由于您没有为m使用RAII锁,因此如果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