Home  >  Q&A  >  body text

c++ - 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()

阿神阿神2765 days ago615

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-17 11:35:30

    If you write the answer on your mobile phone, there is no running code, you just rely on reading.
    It seems that it is probably a problem with multi-threading and object life cycle. After you put try in your second code, io_service is not destructed when it runs to the while statement, which is different from the first code.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 11:35:30

    This exception has nothing to do with boost, but a problem with the object life cycle. The TCPServer object only survives within the scope of {} below try. Once the try code block is executed, the object is destroyed. The thread was not stopped correctly after the TCPServer object was destroyed. Your thread may still be running and using the resources in the destroyed object, causing an exception.

    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;
    

    reply
    0
  • Cancelreply