使用 for_each 和 std::unique_ptr

Using for_each with std::unique_ptr

当我尝试将 for_each 算法与 std::unique_ptr 一起使用时出现以下错误。我在下面的 profile.h 部分放大了它。

奇怪的是,如果我将它更改为 std::shared_ptr,我能够编译,我怀疑它按值获取容器的元素,因此不喜欢对 unique_ptrs 的引用.但是,我希望它是 unique_ptr 理想情况下,因为这些任务应该放在 ToRun_ 容器内,并在任务执行后移至 Completed_ 容器,因此 shared_ptr 不会这对我没有任何好处。

我得到的错误是:

no matching function for call to object of type '(lambda at Profile.cpp:429:54)'

__f(*__first);

其中指的是这行代码:

for_each(ToRun_.begin(), ToRun_.end(), [&os](std::unique_ptr<Task>& e){
  if (e){
    os << e->getName() <<'\n';
  }
});

在将其转换为使用智能指针之前,我使用了原始指针,我可以保证 e->getName()100% 有效。我的困惑是为什么它在这种情况下不起作用?我该怎么做才能让它正常工作?

Profile.h

#include <algorithm>
#include <vector>
#include <map>
#include <iostream>
#include "Task.h"
#include "Global.h" //Where my user defined global functions go

class Profile{
  std::vector<std::unique_ptr<Task>>ToRun_;
  std::vector<std::unique_ptr<Task>>Completed_;
  std::vector<std::string>menu_;
  //Ownership of ofstream object
  std::ofstream& of_;
public:
  Profile (const char* filename, std::ofstream& os, ARAIG_sensors& as);
  virtual ~Profile();
  void run();
  //Executes specified number of tasks user specifies
  void execute (unsigned long tasks);
  void load_menu();
  long show_menu()const;
  long getInput(std::string prompt, int min, long max, menuOption option = NONE);
  //Display all tasks to the screen
  std::ostream& display_todo_tasks (std::ostream& os) const;
  //Display completed tasks to the screen
  std::ostream& display_completed_tasks (std::ostream& os)const;
  //Display next task to the screen
  std::ostream& display_next_task (std::ostream& os) const;
  //Display last completed task
  std::ostream& display_last_task(std::ostream& os)const;
};

Profile.cpp

std::ostream& Profile::display_todo_tasks(std::ostream& os)const{
  //Display all tasks in ToRun container
  if(ToRun_.size() > 0){
    new_line(user_interface_skip_screen);
    std::cout << "\nTasks to be completed\n";
    print_dash(29);
    for_each(ToRun_.begin(), ToRun_.end(), [&os](std::unique_ptr<Task>& e){
      if (e){
        os << e->getName() <<'\n';
      }
    });
    new_line(user_interface_system_message_skip_line - 1);
  }else{
    std::cerr << "There are no tasks to be performed in the task list.";
    std::cerr.flush();
    new_line(user_interface_system_message_skip_line);
  }
  return os;
}
std::ostream& Profile::display_todo_tasks(std::ostream& os)const

您的函数是一个 const 函数。因此,ToRun_ 是一个 const 对象。因此,您从 beginend 获得的迭代器是 const_iterator。因此,当你取消引用它们时你得到的是 const 引用.

您的 lambda 使用非 const 引用。因此不兼容。让它带一个const参考,应该没问题。