I am trying to understand 'future', 'promise' and 'async'. So I copied the following code nearly verbatim from cppreference.com . The compiler gives the error std::promise<int>::promise(const std::promise<int> &)
: attempting to reference a deleted function.
#include "stdafx.h"
#include <iostream>
#include <future>
#include <thread>
int main()
{
// future from a packaged_task
std::packaged_task<int()> task([](){ return 7; }); // wrap the function
std::future<int> f1 = task.get_future(); // get a future
std::thread(std::move(task)).detach(); // launch on a thread
// future from an async()
std::future<int> f2 = std::async(std::launch::async, [](){ return 8; });
// future from a promise
std::promise<int> p;
std::future<int> f3 = p.get_future();
std::thread( [](std::promise<int> p){ p.set_value_at_thread_exit(9); }, //<-- error occurs here
std::move(p) ).detach();
std::cout << "Waiting..." << std::flush;
f1.wait();
f2.wait();
f3.wait();
std::cout << "Done!\nResults are: "
<< f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
}
I see why, the 'promise' p can't be copied due to the copy constructor. But since it is not my class, I can't change it. So my questions are:
1) This is an example from a C++ reference website, does it compile on any other compiler? (I am using VS 2013).
2) What can I do to fix the error and get the example to work as intended?
NOTE: I answered my own question below. But now the example program fails a debug assertion at ...
f3.wait();
So, though my change allows it to compile, now I have a runtime error. Is that due to my change? Or is it another bug? The error is "Debug Error! ... R6010 - abort() has been called".
NOTE: I modified my answer below. I decided to use a pointer instead of a reference.
Sorry, I just figured it out. I changed the function to pass a pointer as follows...
std::thread( [](std::promise<int>* p){ p->set_value_at_thread_exit(9); }, //<-- pointer fixes error
&p).detach();
I had tried using a reference. That fixed the original error but then I ran into a failed debug assertion "Debug Error! ... R6010 - abort() has been called". While debugging, I found the promise destructor being called after the promise task completed but before F3.wait() was called.
So, that answers question #2. I assume the answer to question #1 is 'no'. I will let the sight know about the bug (will edit it if I can).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.