fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <future>
  4.  
  5. class A {
  6. public:
  7. A(int value) : value_(value) {}
  8.  
  9. // Copy constructor
  10. A(const A& other) : value_(other.value_) {
  11. std::cout << "Copy constructor called\n";
  12. }
  13.  
  14. // Move constructor
  15. A(A&& other) noexcept : value_(other.value_) {
  16. other.value_ = 0; // Reset the moved-from object
  17. std::cout << "Move constructor called\n";
  18. }
  19.  
  20. int value() const { return value_; }
  21.  
  22. private:
  23. int value_;
  24. };
  25.  
  26. void process(const A& obj) {
  27. // Simulate some work
  28. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  29. std::cout << "Processing object with value: " << obj.value() << std::endl;
  30. }
  31.  
  32. int main() {
  33. std::vector<A> objects;
  34. objects.push_back(A(1));
  35. objects.push_back(A(2));
  36. objects.push_back(A(3));
  37.  
  38. std::vector<std::future<void>> futures;
  39.  
  40. std::cout << "Start processing\n";
  41. for (const auto& obj : objects) {
  42. // Capture 'obj' by reference in the lambda
  43. futures.push_back(std::async(std::launch::async,
  44. [&obj]() { process(obj); }));
  45. }
  46.  
  47. // Wait for all threads to finish
  48. for (auto& f : futures) {
  49. f.get();
  50. }
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Move constructor called
Move constructor called
Move constructor called
Move constructor called
Move constructor called
Move constructor called
Start processing
Processing object with value: 3
Processing object with value: 2
Processing object with value: 1