简体   繁体   English

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

[英]boost::asio::io_service check if null

I am using boost 1.55 ( io_service doc ). 我正在使用Boost 1.55( io_service doc )。 I need to call the destructor on my io_service to reset it after power is cycled on my serial device to get new data. 在串行设备上重新打开电源以获取新数据后,我需要在io_service上调用析构函数以将其重置。 The problem is that when the destructor is called twice (re-trying connection), I get a segmentation fault. 问题是,当析构函数被调用两次(重试连接)时,出现分段错误。

In header file 在头文件中

boost::asio::io_service io_service_port_1;

In function that closes connection 在关闭连接的功能中

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?

The following does not work: 以下内容不起作用:

if (io_service_port_1)
if (io_service_port_1 == NULL)

Thank you. 谢谢。

If you need manual control over when the object is created and destroyed, you should be wrapping it in a std::unique_ptr object. 如果需要手动控制对象的创建和销毁时间,则应将其包装在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.

Generally speaking, you should never directly call ~object_name(); 一般来说,您永远不要直接调用~object_name(); . Ever. 曾经 Ever. 曾经 Ever. 曾经 There's several reasons why: 原因有几个:

  • As a normal part of Stack Unwinding, this will get called anyways when the method returns. 作为堆栈展开的正常部分,方法返回时无论如何都会调用它。
  • delete ing a pointer will call it. delete指针将调用它。
  • "Smart Pointers" (like std::unique_ptr and std::shared_ptr ) will call it when they self-destruct. 当它们自毁时,“智能指针”(如std::unique_ptrstd::shared_ptr )将调用它。

Directly calling ~object_name(); 直接调用~object_name(); should only ever be done in rare cases, usually involving Allocators, and even then, there are usually cleaner solutions. 仅在极少数情况下才应该这样做,通常涉及分配器,即使那样,通常也存在更清洁的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM