我想創建一些Timer
類,它每N秒打印一次「text」,其中N將在構造函數中初始化。C++ bad_weak_ptr錯誤
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <iostream>
class Timer : public boost::enable_shared_from_this<Timer>
{
public:
Timer (const double interval) : interval_sec(interval)
{
io_service_ = new boost::asio::io_service;
timer_ = new boost::asio::deadline_timer (* io_service_);
start();
io_service_ -> run();
}
void start ()
{
timer_ -> expires_from_now(boost::posix_time::seconds(0));
timer_ -> async_wait(boost::bind(&Timer::handler
, shared_from_this()
, boost::asio::placeholders::error
)
);
}
private:
void handler(const boost::system::error_code& error)
{
if (error)
{
std::cerr << error.message() << std::endl;
return;
}
printf("text\n");
timer_ -> expires_from_now(boost::posix_time::seconds(interval_sec));
timer_ -> async_wait(boost::bind(&Timer::handler
, shared_from_this()
, boost::asio::placeholders::error
)
);
}
private:
boost::asio::io_service * io_service_;
boost::asio::deadline_timer * timer_;
double interval_sec;
};
int main()
{
boost::shared_ptr<Timer> timer(new Timer (10));
return 0;
}
但我有bad_weak_ptr
錯誤。
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_weak_ptr> >'
what(): tr1::bad_weak_ptr
Aborted
我在做什麼錯,我該如何解決?
你是否已經在調試器中加入了代碼?我猜''main()'在定時器觸發之前會返回,導致'timer'被破壞。你確定'async_wait'持有共享對象嗎? – 2011-04-05 21:30:36
你可能也想做一些關於內存泄漏的事情。用'new'創建成員幾乎不是一個好主意。 – 2011-04-05 23:10:43
在這個問題上有點OT,但是它是第一個搜索'boost :: bad_weak_ptr'的結果,所以我會在這裏寫這個。一個很好的'boost :: bad_weak_ptr'異常(拋出'boost :: exception_detail :: clone_impl'''後調用'terminate)也會拋出,如果試圖用'std :: shared_ptr '替換'boost :: shared_ptr ',所以要小心。 :) –
Avio
2014-10-14 13:17:27