Question

I'm currently doing the boost asio tutorial, and I'm running into a problem with bind: Of course the default code works: http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/tutorial/tuttimer3/src.html

but when I'm trying to use references instead of pointers in the print function, I get compiler errors:

error: use of deleted function ‘asio::basic_deadline_timer<boost::posix_time::ptime>::basic_deadline_timer(const asio::basic_deadline_timer<boost::posix_time::ptime>&)’

     t.async_wait(boost::bind(do_sth1,asio::placeholders::error,t, count));

My modified code:

#include <iostream>
#include <asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

void do_sth1(const asio::error_code& ,asio::deadline_timer& t, int& count )
{
  if(count<=5){
    (count)++;
    t.expires_at(t.expires_at()+boost::posix_time::seconds(2));
    t.async_wait(boost::bind(do_sth1,asio::placeholders::error,t, count));
  }
  std::cout<<count<<"\n";
}

void do_sth2(const asio::error_code& ){
  std::cout<<"Yo\n";
}

int main()
{
  int count =0;
  asio::io_service io;

  asio::deadline_timer t1(io, boost::posix_time::seconds(1));
  asio::deadline_timer t2(io, boost::posix_time::seconds(3));
  t1.async_wait(boost::bind(do_sth1,asio::placeholders::error,t1,count));
  t2.async_wait(do_sth2);

  io.run();
  std::cout << "Hello, world!\n";

  return 0;
}
Was it helpful?

Solution

Deleted functions have been introduced only recently to C++ -- see e.g. here on MSDN. Previously this was worked around by declaring the method as private. Whatever the way it is done, it means that someone declared an otherwise implicitly created method as deleted, so that nobody could (even accidentally) call it. This is used for example to disallow copying objects which it does not make sense to copy (by deleting the copy constructor).

This is exactly your case, as the deleted function's name ‘asio::basic_deadline_timer::basic_deadline_timer(const asio::basic_deadline_timer&) indeed reveals that a copy constructor was supposed to be called. boost::deadline_timers cannot be copied.

But why is the timer object being copied? Because boost::bind by default stores the bound parameters by value. If you need to pass a reference, you need to use boost::ref as follows:

t1.async_wait(boost::bind(do_sth1,asio::placeholders::error,boost::ref(t1),boost::ref(count)));

I.e. even for the count variable, which would not cause a compiler error, but wouldn't work (would not modify the variable in main()).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top