c++ - boost::shared_ptr 断言错误与 boost::asio:io_service

标签 c++ boost shared-ptr assertion

我目前正在尝试了解 boost::asio-API。在我的一个类(class)中,我使用 boost::shared_ptr 以这种方式引用 io_service:

class myClass : public boost::asio::serial_port
{
public: 
    myClass(std::string Port);

private:
    boost::shared_ptr<boost::asio::io_Service> _io_service_ptr;
};

根据那个实现是:

myClass::myClass(std::string Port) : _io_service_ptr(new boost::asio::io_service), 
boost::asio::serial_port(*_io_service_ptr, Port)
{
    //do stuff
}

当我这样做时,出现错误:断言失败! px != 0 [...]

当对其他 boost::asio 对象(如 boost::asio::io_service::work(service))使用相同的模式时,它工作正常。我对 io_service 做错了什么?

最佳答案

基类在成员之前初始化,因此 io_service 直到您尝试取消引用未初始化的指针以将引用传递给基类之后才会创建。

但是从 serial_port 派生似乎很奇怪;为什么不使用聚合呢?确保服务在使用它之前声明:

class myClass {
public:
    myClass(std::string port) : serial_port(io_service, port) {}

    // public interface to interact with the serial port and whatever else

private:
    boost::asio::io_service io_service; // or a shared pointer if there's a good reason
    boost::asio::serial_port serial_port;
};

您也可能希望与多个对象共享一项服务,因此也许它根本不应该属于此类:

class myClass {
public:
    myClass(boost::asio::io_service & io_service, std::string port) : 
        serial_port(io_service, port) 
    {}

    // public interface to interact with the serial port and whatever else

private:
    boost::asio::serial_port serial_port;
};

关于c++ - boost::shared_ptr 断言错误与 boost::asio:io_service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22229618/

相关文章:

c++ - 使用 pthread_setspecific 和 pthread_getspecific 存储指向 std::map 实例的指针

c++ - LNK1104 : cannot open file 'libboost_program_options-vc100-mt-sgd-1_56.lib'

C++、模板或指向成员函数的指针

c++ - The C++ Programming Language 中的弱指针示例

c++ - 在构造函数中注册 weak_ptr 观察者

类中的 C++ 对象构造

c++ - 从 C# 调用 C++ 函数

c++ - Qt paintEvent() 异常触发

c++ - 在 C++ 中将日期转换为以毫秒为单位的时间?

c++ - 如何通过共享 ptr 访问类的成员函数到共享 ptr?