2014-04-17 62 views
0

我目前在做提升ASIO教程,和我正在與綁定一個問題: 當然默認的代碼工作: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));

我修改後的代碼:

#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; 
} 

回答

2

刪除的功能已被最近才引入C++ - 參見例如here on MSDN。以前這是通過聲明該方法爲私有的。無論它做了什麼,它都意味着有人宣佈一種被隱式創建的方法被刪除,這樣任何人都無法(甚至偶然地)調用它。這用於例如不允許拷貝對象(它通過刪除拷貝構造函數)來進行拷貝沒有意義。

這正是你的情況,因爲刪除函數的名稱‘asio::basic_deadline_timer::basic_deadline_timer(const asio::basic_deadline_timer&)確實揭示了複製構造函數應該被調用。 boost::deadline_timer s不能被複制。

但是爲什麼計時器對象被複制?因爲boost::bind默認按值存儲綁定參數。如果你需要傳遞一個參考,你需要使用boost::ref如下:

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

即即使對於計數變量,它不會導致編譯器錯誤,但不會工作(不會修改main()中的變量)。

+0

啊,我們走吧。現在它工作得很好。謝謝。我閱讀了關於明確刪除的函數,但無法將其應用於特定的錯誤位置。現在我可以更好地瞭解這張照片。 – jjstcool

+0

太棒了!對不起,如果有太多的毛病,我想爲未來提供一些背景和指導。 _(請將答案標記爲已接受,以便它不再出現在未回答的問題列表中)。_ – Yirkha

+0

不,它不是太多,謝謝指出這一切。案例關閉:-) – jjstcool