在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构造函数不能保证不抛出异常,所以你有一个异常安全问题。由于您没有为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
相关文章:
- lower_bound()返回最后一个元素
- 使用std::transform将一个范围的元素添加到另一个范围中
- 我想访问std::unique_ptr中的一个特定元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 删除映射和分割错误中的一个过去结束元素
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 仅显示链表的最后一个元素
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 查找最小的下一个更大的元素
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- 选择一个元素而不是一个对象的数组的原因
- std::矢量保存 只推送最后一个元素
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素