c++ - boost::asio::io_service 检查是否为空

标签 c++ boost-asio

我正在使用 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_ptrstd::shared_ptr)将在自毁时调用它。

直接调用 ~object_name(); 只应在极少数情况下进行,通常涉及分配器,即便如此,通常也有更简洁的解决方案。

关于c++ - boost::asio::io_service 检查是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41152794/

相关文章:

c++ - 使用模板类型将参数传递给函数

c++ - 使用 CGAL 获取多边形相交线

c++ - 在 Windows 上获取根 CA 证书的可靠方法

c++ - boost ASIO streambuf

c++ - 为什么在 C++ 中的类初始化之前使用作用域运算符 (::)?

c++ - 检查字符串是否包含数字的函数

c++ - 无法访问类 'A' 中声明的 protected 成员

c++ - 如何通过 HTTPS POST 正确发送二进制数据?

c++ - 什么是 boost::asio::write 保证(ACK,校验和)?

boost-asio - 我可以在执行读写的 2 个线程之间共享 boost::asio::tcp::socket 对象吗