boost::asio::io_service 检查是否为空
boost::asio::io_service check if null
我正在使用 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 的正常部分,无论如何都会在方法 returns 时调用它。
delete
调用指针将调用它。
- "Smart Pointers"(如
std::unique_ptr
和std::shared_ptr
)会在自毁时调用它。
只应在极少数情况下直接调用 ~object_name();
,通常涉及分配器,即使那样,通常也有更简洁的解决方案。
我正在使用 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 的正常部分,无论如何都会在方法 returns 时调用它。
delete
调用指针将调用它。- "Smart Pointers"(如
std::unique_ptr
和std::shared_ptr
)会在自毁时调用它。
只应在极少数情况下直接调用 ~object_name();
,通常涉及分配器,即使那样,通常也有更简洁的解决方案。