我正在使用 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)
谢谢。
最佳答案
如果您需要手动控制对象的创建和销毁时间,您应该将其包装在 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();
。曾经。曾经。曾经。有几个原因:
- 作为 Stack Unwinding 的正常部分,无论如何都会在方法返回时调用它。
删除
一个指针会调用它。- “智能指针”(如
std::unique_ptr
和std::shared_ptr
)将在自毁时调用它。
直接调用 ~object_name();
只应在极少数情况下进行,通常涉及分配器,即便如此,通常也有更简洁的解决方案。
关于c++ - boost::asio::io_service 检查是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41152794/