2017-01-30 28 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這樣的「談話」。關於手術的好處_被遺棄。 –

相關問題