Search code examples
c++concurrent.futures

pushing packaged task into container causes C2280 error in VS2013


I want to use packaged_tasks to add tasks to a container. I create a task, bind it to a number and try to push it into my deque. I get compiler error C2280 (VS2013) on the push_back. Here is the code:

void DoTask( int i )
{
  std::cout << "int value: " << i << std::endl;
}

std::deque< std::packaged_task< void() > > task_q;

int _tmain(int argc, _TCHAR* argv[])
{
  std::packaged_task< void() > t( std::bind( DoTask, 3 ) );
  task_q.push_back( t ); // <-- C2280 error

  return 0;
}

I got this sample code from a YouTube Bo Qian lecture called "C++ Threading #9: packaged_task". Here is some error code text:

error C2280: 
    'std::packaged_task<void (void)>::packaged_task(const std::packaged_task<void (void)> &)' : attempting to reference a deleted function... see declaration of 'std::packaged_task<void (void)>::packaged_task'...while compiling class template member function 'void std::allocator<_Ty>::construct(_Ty *,const _Ty &)'
    1>          with
    1>          [
    1>              _Ty=std::packaged_task<void (void)>"

Here is the code after two corrections (move task and non-void return value):

int DoTask( int i ) // non-void return value
{
  return i;
}

std::deque< std::packaged_task< int() > > task_q; // bind eliminates need for arg (Bo Qian lecture)

int _tmain( int argc, _TCHAR* argv[] )
{
  std::packaged_task< int() > t( std::bind( DoTask, 3 ) ); // bind eliminates need for arg
  task_q.push_back( std::move( t ) ); // <-- move not copy

  return 0;
}

Solution

  • Copy constructor of packaged_task is deleted. Use:

    task_q.push_back( std::move(t) );