2016-12-14 75 views
0

我正在使用boost 1.55(io_service doc)。我需要在io_service上调用析构函数,以便在串行设备上通电后重置它以获取新数据。问题是,当析构函数被调用两次(重新尝试连接)时,我得到了分段错误。boost :: asio :: 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) 

谢谢。

+1

你不能摧毁一个物体两次。一旦它被摧毁,它就消失了。既然你明确调用了析构函数,你是不是很想实例化一个新的对象实例?为什么你明确地调用析构函数呢? –

+0

@CaptainObvlious我在上面陈述我的理由(串行设备通电)。我如何实例化一个新的'io_service'实例? – xinthose

+0

在堆上分配它并在第一次将它摧毁时将其设置为null?或者如果它提供了一些机制来做你想做的事情,可能会使用'boost :: optional'。 – Arunmu

回答

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();。永远。永远。永远。原因如下:

  • 作为Stack Unwinding的一个正常部分,当方法返回时,它将被调用。
  • delete ing指针会调用它。
  • “智能指针”(如std::unique_ptrstd::shared_ptr)会在自毁时调用它。

直接调用~object_name();应该永远只能在极少数情况下进行,通常涉及分配器,即使这样,通常有更清洁的解决方案。

相关问题