检查新添加的unique_ptr到priority_queue的位置

问题描述 投票:1回答:1

我将设计切换为使用智能指针,但遇到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-pointers priority-queue
1个回答
0
投票

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

bool foo (std::unique_ptr<SchedulerTask> task) {
  auto const * taskPtr = task.get();
  eventList_.push(std::move(task));
  return taskPtr == eventList_.top().get();
}
© www.soinside.com 2019 - 2024. All rights reserved.