vendredi 27 novembre 2020

How comes std::packaged_task is making a copy of my forwarded reference parameter?

#include <functional>
#include <iostream>
#include <future>

template <typename Func, typename... Args>
auto exec(Func&& func, Args&&... args)
  -> std::shared_ptr<std::packaged_task<typename std::result_of<Func(Args...)>::type()>> {
  using PackedTask = std::packaged_task<typename std::result_of<Func(Args...)>::type()>;
  func(args...);
  auto task = std::make_shared<PackedTask>(
      std::bind(std::forward<Func>(func), std::forward<Args>(args)...));
  return task;
}

int main() {
  auto i = 10;
  auto func = [](int& i) {
    std::cout << i << "\n";
  };
  i = 20;
  auto task = exec(func, i);
  i = 30;
  (*task)();
  return 0;
}

Compiled with g++ (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)

g++ test.cpp -pthread

produces

$ ./a.out
20
20

I am experiencing with std::packaged_task and I do not understand why the i variable ends up being copied and how to avoid doing so while still passing it as an argument of my exec() function.

Aucun commentaire:

Enregistrer un commentaire