我可以使用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。我最感興趣的是這樣做的現有語法。我知道我可以自定義代碼來自己做。我也知道我可以保持定時器手動,但我想避免這一點。
謝謝。這也是我計劃要做的。你對在這種情況下使用什麼智能指針類型有任何偏好(在boost和STL的範圍內)? –
我用boost :: shared_ptr和std :: shared_ptr。我想unqiue_ptr也可以工作,如果對象然後移動到處理程序對象。但我沒有這方面的經驗,因爲無論如何我需要shared_ptr。 – Matthias247
不幸的是,當按照建議使用額外參數時,我得到了Visual Studio 2012編譯器的編譯錯誤:錯誤C2039:'result_type':不是'全局命名空間'錯誤C2208:'boost :: _ bi :: type'的成員:沒有成員使用此類型定義錯誤C2825:'F':必須是一個類或命名空間,後跟'::' –