dimanche 27 mai 2018

How exactly std::async is executed

I wonder how does the following code work?

#include <thread>
#include <future>
#include <set>
#include <iostream>
struct Task;
std::set<const Task*> dead_tasks;
struct Task
{
   ~Task() { dead_tasks.insert(this); std::cout << "dtor\n";}
   Task() { std::cout << "ctor\n";}
   Task(Task&&) { std::cout << "move-ctor\n";}
   void operator()() const { std::cout << "func()\n"; }
};
int main(){
   std::cout << dead_tasks.size() << '\n';
   std::async(std::launch::async, Task());
   std::cout << dead_tasks.size() << '\n';
}

This code prints

0 ctor move-ctor move-ctor dtor func() dtor dtor 3

If we use std::launch::deferred instead of std::launch::async we will get

0 ctor move-ctor move-ctor dtor dtor dtor 3

So in the latter we miss the member function call. Why? I can understand the presence of the call to the default constructor and the call to the move constructor. Task() calls the default constructor, then std::async does a call to the move constructor... However I missed the idea behind the second call to the move constructor and the call to the member function. I can think that the second move constructor is called by std::future, can't I?

Aucun commentaire:

Enregistrer un commentaire