I have been trying to capture packaged_task into lambda, but I've failed.
I understand move-semantics at all, also read some modern literature and I was thinking I didn't miss anything. Also I have read Josuttis's move semantics book, and ISO topic about generalized lambda captures and similar case at ISO C++ 14 Language Extensions
I have next code:
#include <thread>
#include <vector>
#include <functional>
#include <queue>
#include <condition_variable>
#include <mutex>
#include <future>
#include <type_traits>
#include <iostream>
// #include's for below code and other purposes
int main() {
auto f = []() { return 1; };
std::queue<std::function<void()>> q;
std::packaged_task<int()> pack(f);
q.emplace([p = std::move(pack)] () mutable { p(); });
return 0;
}
Here I create simple queue of functions, holding some 'void ()' and packaged_task, passing 'f' of 'int' return type.
Then I'm trying to move packaged_task into lambda to use it later in other thread(i need to use it in other thread, which will execute it much more later, when 'pack' will be destroyed and this is why I can't take it by reference)
Seems all's good, but when I compile it with "g++ main.cpp -o main -std=c++14" (and even with c++17), g++ tells me this:
/usr/include/c++/9/bits/std_function.h:176:6: error: use of deleted function ‘main()::::(const main()::&)’
176 | new _Functor(*__source._M_access());
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:19:32: note: ‘main()::::(const main()::&)’ is implicitly deleted because the default definition would be ill-formed:
19 | q.emplace([p = std::move(pack)] () mutable { p(); });
| ^
main.cpp:19:32: error: use of deleted function ‘std::packaged_task<_Res(_ArgTypes ...)>::packaged_task(const std::packaged_task<_Res(_ArgTypes ...)>&) [with _Res = int; _ArgTypes = {}]’
In file included from main.cpp:8:
/usr/include/c++/9/future:1511:7: note: declared here
1511 | packaged_task(const packaged_task&) = delete;
| ^~~~~~~~~~~~~
Also I can just use shared_ptr to solve this problem by passing copy of it to lambda, but this way of solving problem seems too ugly. So why I got error with copy constructing if I tryed to move it and how can I fix it?