Reputation: 285
I am currently trying to understand the boost::asio-API. in one of my classes I use a boost::shared_ptr to reference an io_service in this way:
class myClass : public boost::asio::serial_port
{
public:
myClass(std::string Port);
private:
boost::shared_ptr<boost::asio::io_Service> _io_service_ptr;
};
And the implementation according to that is:
myClass::myClass(std::string Port) : _io_service_ptr(new boost::asio::io_service),
boost::asio::serial_port(*_io_service_ptr, Port)
{
//do stuff
}
When I do this, i get the error: Assertion failed! px != 0 [...]
When use the same pattern for other boost::asio objects (like boost::asio::io_service::work(service)) it works fine. What did i do wrong with the io_service?
Upvotes: 0
Views: 432
Reputation: 254411
Base classes are initialised before members, so the io_service
is not created until after you try to dereference the uninitialised pointer to pass a reference to the base class.
But deriving from serial_port
seems rather odd; why not use aggregation instead? Make sure the service is declared before anything that uses it:
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;
};
It's also likely that you'd want to share one service with many objects, so perhaps it shouldn't be owned by this class at all:
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;
};
Upvotes: 2