簡體   English   中英

在C ++ 11中從std :: deque移動一個元素

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM