boost::thread and std::unique_ptr
Is it somehow possible to pass an std::unique_ptr as a parameter to a 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))开发者_Go百科;
}
This compiles and runs 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 has to be in C++0x mode. I don't know if the boost move emulation is good enough to do this or not.
A std::unique_ptr is, as the name suggests, unique. There can be only one!
Now, if your thread function takes a std::unique_ptr&&, and you use std::move to move the parameter in the thread function, then you can pass the std::unique_ptr. But then your copy will be empty, since you moved it to the other thread.
If std::move does not work, then your compiler or standard library may have bugs in it. I imagine that transferring ownership across threads like this isn't a common occurrence. And C++11 is still fairly new.
Are you sure your problem is with the unique_ptr? Why does your example use new to create your functor? That line should just read:
boost::thread th(TestThread(), std::move(ptr));
精彩评论