我正在使用boost 1.55(io_service doc)。我需要在我的io_service上调用析构函数,在我的串行设备上重启电源后重置它以获取新数据。问题是当析构函数被调用两次(重新尝试连接)时,我会遇到分段错误。
在头文件
中boost::asio::io_service io_service_port_1;
关闭连接的功能
io_service_port_1.stop();
io_service_port_1.reset();
io_service_port_1.~io_service(); // how to check for NULL?
// do I need to re-construct it?
以下不起作用:
if (io_service_port_1)
if (io_service_port_1 == NULL)
谢谢。
答案 0 :(得分:2)
如果您需要手动控制何时创建和销毁对象,则应将其包装在std::unique_ptr
对象中。
std::unique_ptr<boost::asio::io_service> service_ptr =
std::make_unique<boost::asio::io_service>();
/*Do stuff until connection needs to be reset*/
service_ptr->stop();
//I don't know your specific use case, but the call to io_service's member function reset is probably unnecessary.
//service_ptr->reset();
service_ptr.reset();//"reset" is a member function of unique_ptr, will delete object.
/*For your later check*/
if(service_ptr) //returns true if a valid object exists in the pointer
if(!service_ptr) //returns true if no object is being pointed to.
一般来说,您不应该直接致电~object_name();
。永远。永远。永远。原因有以下几种:
delete
指针会调用它。std::unique_ptr
和std::shared_ptr
)会在自毁时调用它。直接调用~object_name();
应该只在极少数情况下进行,通常涉及分配器,即使这样,通常也会有更清晰的解决方案。