boost :: asio :: io_service检查是否为null

boost::asio::io_service check if null

本文关键字:是否 null 检查 asio io boost service      更新时间:2023-10-16

我正在使用boost 1.55(io_service doc)。我需要在我的io_service上调用destructor,以在循环串行设备上循环以获取新数据后将其重置。问题是,当攻击器被称为两次(重试连接)时,我会得到一个分段错误。

在标题文件中

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();。曾经。曾经。曾经。有几个原因:

  • 作为堆栈放松的正常部分,当方法返回时,这将被调用。
  • delete指针将其称为。
  • "智能指针"(例如std::unique_ptrstd::shared_ptr)会在自我毁灭时称其为称。

直接调用~object_name();只能在极少数情况下进行,通常涉及分配,即使那样,通常也有更干净的解决方案。