Boost :: thread and std :: unique_ptr
Is it possible to pass std :: unique_ptr as parameter to boost :: thread constructor? If not, what is the best workaround?
A small example:
// errors: g++ uniqueptr_thread.cpp -std=c++0x
#include <iostream>
#include <memory>
#include <boost/thread.hpp>
class TestThread{
public:
void operator()(std::unique_ptr<int> val){
std::cout << "parameter: " << val << std::endl;
}
};
int main(int argc, char* argv[]){
std::unique_ptr<int> ptr(new int(5));
boost::thread th( new TestThread(), std::move(ptr));
}
+2
source to share
3 answers
This compiles and works for me:
#include <iostream>
#include <memory>
#include <thread>
class TestThread{
public:
void operator()(std::unique_ptr<int> val){
std::cout << "parameter: " << *val << std::endl;
}
};
int main()
{
std::unique_ptr<int> ptr(new int(5));
std::thread th( TestThread(), std::move(ptr));
th.join();
}
But it must be in C ++ 0x mode. I don't know if boost emulation is right for this or not.
+2
source to share
A std :: unique_ptr, as the name suggests, is unique. There can be only one!
Now, if your stream function accepts std :: unique_ptr & &, and you use std :: move to move the parameter in the stream function, you can pass std :: unique_ptr. But then your copy will be empty since you moved it to another thread.
If std :: move doesn't work, your compiler or standard library may have errors. My guess is that transferring ownership of such streams is not common. And C ++ 11 is still pretty new.
+2
source to share