首页 > 解决方案 > 检查新添加的 unique_ptr 到 priority_queue 的位置

问题描述

我正在切换我的设计以使用智能指针,我遇到了 std::priority_que 的问题

我有一种方法可以将新任务插入队列,并在新任务到达队列顶部时发出信号:

bool foo(SchedulerTask* task)
{
  eventList_.push(task);
  return task == eventList_.top();
}

将 SchedulerTask 包装到 unique_ptr 后,我遇到了在容器中检查其优先级的问题。将对象移入队列后,我无法再次使用它进行比较。我最终缓存了比较器成员并将其与顶部对象进行比较:

bool foo(std::unique_ptr<SchedulerTask> task)
{
  const auto prio = task->getCycle(); // my priority_queue compares objects by getCycle() value

  eventList_.push(std::move(task));

  return prio >= eventList_.top()->getCycle();;
}

可以做得更好吗?

标签: c++smart-pointerspriority-queue

解决方案


正如@Sam Varschavchik 暗示的那样,您可以与原始指针进行比较。即你会做类似的事情:

bool foo (std::unique_ptr<SchedulerTask> task) {
  auto const * taskPtr = task.get();
  eventList_.push(std::move(task));
  return taskPtr == eventList_.top().get();
}

推荐阅读