This question already has an answer here:
So I'm trying to pass a std::unique_ptr
as a parameter to a function that is launched in a separate thread, and I'm getting a strange error at compile time that reads:
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(1149): error C2280: 'std::unique_ptr<Widget,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
A simplified version of this code, that still reproduces the same issue is:
#include <thread>
#include <memory>
#include <iostream>
class Widget
{
public:
Widget() : m_data(0)
{
}
void prepareData(int i)
{
m_data = i;
}
int getData() const
{
return m_data;
}
private:
int m_data;
};
void processWidget(std::unique_ptr<Widget> widget)
{
std::cout << widget->getData() << std::endl;
}
int main()
{
std::unique_ptr<Widget> widget(new Widget());
widget->prepareData(42);
std::thread t(processWidget, std::move(widget));
t.join();
return 0;
}
My guess is that there is something wrong with the destruction of the Widget
object from main(
), however I cannot pinpoint the issue. Is it necessary to do something additional to cleanup that variable? By the way, I'm using VS2013.
You are not allowed to make copy of unique_ptr, therefore the copy constructor is disabled. That is pointing the compiler error.
You can fix it with a reference: