首页 > boost异常

boost异常

这个问题有点奇怪,也不知道怎么描述。
报错的位置是在VC\crt的源码dbgheap.c中的504行,应该是用malloc申请内存的时候报错。
源码和报错信息如下

int main()
{
try
{
boost::asio::io_service io_service;
boost::asio::ip::tcp::endpoint en(boost::asio::ip::address::from_string("127.0.0.1"), 10086);
TcpServer server(io_service, en);
server.run();
}
catch (std::exception& e)
{
printf("caught exception: %s", e.what());
}
while(true)
{
printf("please enter a command: |quit|new|stock|sold| \n");

}
return 0;

}

void TcpServer::run()
{
printf("start io_service thread!\n");
boost::shared_ptr thread(new boost::thread(boost::bind(&io_service::run, &m_Service)));
m_ServiceThreads.push_back(thread);
}

如果我把try catch扩展到连while循环都包括进去,则不会出现任何异常。而且一切正常。。代码如下:

int main()
{
try
{
boost::asio::io_service io_service;
boost::asio::ip::tcp::endpoint en(boost::asio::ip::address::from_string("127.0.0.1"), 10086);
TcpServer server(io_service, en);
server.run();

    while(true)
    {
        printf("please enter a command: |quit|new|stock|sold| \n");
    }
}
catch (std::exception& e)
{
    printf("caught exception: %s", e.what());
}
return 0;

}

有人能告诉我这是为什么吗?或者问题是出在哪呢?
FYI:我不想阻塞主线程,所以不希望用thread.join()


这个异常跟boost没有关系,而是对象生命周期的问题,TCPServer对象只在try的下面{}的范围内生存,一旦try的代码块执行完毕,对象也就销毁了。TCPServer对象销毁后没有正确停止线程,你的线程里可能还在运行并使用了这个销毁对象里面的资源,所以导致了异常。

try
{ 
    boost::asio::io_service io_service;
    boost::asio::ip::tcp::endpoint en(boost::asio::ip::address::from_string("127.0.0.1"),10086);
    TcpServer server(io_service, en);
    server.run();
}
catch (std::exception& e)
{
    printf("caught exception: %s", e.what());
}

//server对象在这里已经析构销毁了
while(true)
{
    printf("please enter a command: |quit|new|stock|sold| \n");
}
return 0;

在手机上写的答案,就没有运行代码了,光靠看的。
看样子多半是多线程和对象生命周期的问题,你第二个代码把try提出来以后,io_service在运行到while语句的时候是没有析构的,这点不同于于第一个代码。

【热门文章】
【热门文章】