2017-01-30 29 views
0

我可以使用boost :: bind使结果函数对象存储一个对象,该对象不会被声明为绑定目标函数的参数吗?例如:我可以使用boost :: bind存储一个不相关的对象吗?

void Connect(const error_code& errorCode) 
{ 
    ... 
} 

// Invokes Connect after 5 seconds. 
void DelayedConnect() 
{ 
    boost::shared_ptr<boost::asio::deadline_timer> timer = 
     boost::make_shared<boost::asio::deadline_timer>(ioServiceFromSomewhere); 

    timer->expires_from_now(
     boost::posix_time::seconds(5)); 

    // Here I would like to pass the smart pointer 'timer' to the 'bind function object' 
    // so that the deadline_timer is kept alive, even if it is not an actual argument 
    // to 'Connect'. Is this possible with the bind syntax or similar? 
    timer->async_wait(
     boost::bind(&Connect, boost::asio::placeholders::error)); 
} 

ps。我最感兴趣的是这样做的现有语法。我知道我可以自定义代码来自己做。我也知道我可以保持定时器手动,但我想避免这一点。

回答

2

是的,你可以通过绑定额外的参数来做到这一点。我常常用asio做这个,例如以便在异步操作期间保持缓冲区或其他状态。

您也可以事后通过扩展处理程序签名,利用它们从处理程序访问这些额外的参数:

void Connect(const error_code& errorCode, boost::shared_ptr<asio::deadline_timer> timer) 
{ 
} 

timer.async_wait(
    boost::bind(&Connect, boost::asio::placeholders::error, timer)); 
+0

谢谢。这也是我计划要做的。你对在这种情况下使用什么智能指针类型有任何偏好(在boost和STL的范围内)? –

+0

我用boost :: shared_ptr和std :: shared_ptr。我想unqiue_ptr也可以工作,如果对象然后移动到处理程序对象。但我没有这方面的经验,因为无论如何我需要shared_ptr。 – Matthias247

+0

不幸的是,当按照建议使用额外参数时,我得到了Visual Studio 2012编译器的编译错误:错误C2039:'result_type':不是'全局命名空间'错误C2208:'boost :: _ bi :: type'的成员:没有成员使用此类型定义错误C2825:'F':必须是一个类或命名空间,后跟'::' –

1

是的,你可以简单地绑定“太多”参数,并且它们不会传递给底层处理程序。请参阅Why do objects returned from bind ignore extra arguments?

这是可以的,除非您需要与Connect“交谈”计时器对象。

PS。另外,当定时器被破坏时,不要忘记预计定时器完成时间为operation_abandoned

+0

确定。我想我可以做前面的回答中描述的Matthias247这样的“谈话”。关于手术的好处_被遗弃。 –

相关问题