我目前正在做 boost asio 教程,我遇到了绑定(bind)问题:
当然默认代码有效:http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/tutorial/tuttimer3/src.html
但是当我尝试在打印函数中使用引用而不是指针时,会出现编译器错误:
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;
}
最佳答案
删除函数最近才被引入到 C++ 中——参见例如here on MSDN .以前,这是通过将方法声明为私有(private)来解决的。无论以何种方式完成,这意味着有人将一个以其他方式隐式创建的方法声明为已删除,因此没有人可以(甚至意外地)调用它。例如,这用于禁止复制没有意义的对象(通过删除复制构造函数)。
这正是您的情况,因为已删除函数的名称 ‘asio::basic_deadline_timer::basic_deadline_timer(const asio::basic_deadline_timer&)
确实表明应该调用复制构造函数。 boost::deadline_timer
s 无法复制。
但是为什么要复制计时器对象呢?因为boost::bind
默认情况下按值存储绑定(bind)参数。如果需要传递引用,需要使用 boost::ref
如下:
t1.async_wait(boost::bind(do_sth1,asio::placeholders::error,boost::ref(t1),boost::ref(count)));
IE。即使对于 count 变量,它也不会导致编译器错误,但不会起作用(不会修改
main()
中的变量)。
关于c++ - 在 boost::bind 中使用已删除的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23122332/