Remove all handlers from a boost::asio::io_service without calling them

☆樱花仙子☆ 提交于 2019-12-18 19:07:03

问题


I want to remove all handlers from an IO_service right before I reuse it. Is this possible?

I'm writing unit tests that involve an asio::io_service. In between each test case I want to clear the handlers from the global io_service. I thought that io_service::reset would to that but it doesn't. reset() only allows the io_service to be resumed. All of the handlers from the last test case are still queued up.

I only need to do this for unit testing so any crazy hack would work.


More info:

The io_service is from a deadline_timer member variable. The deadline_timer is part of the code I'm testing so I can't change how it's constructed. I get a hold of its io_service via the deadline_timer's get_io_service method.


回答1:


Well, I racked my brain on this for a few days and came up with a workable solution. It's the mother of all hacks.

void clear( boost::asio::io_service& service )
{
    service.stop();
    service.~io_service();
    new( &service ) boost::asio::io_service;
}

I'm not sure how safe this would be for productions code. But so far it seems to work (no segfaults, no weird behavior).



来源:https://stackoverflow.com/questions/2314816/remove-all-handlers-from-a-boostasioio-service-without-calling-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!