Search code examples
c++boostboost-asioshared-ptr

Spawning new async request from an asio handler


I'm trying to get my feet wet with ASIO and thought a good first project would be a simple web crawler: download an html page, find the links in it, download all the links.

I have tried modifying the ASIO http client example to use enable_shared_from_this instead of a raw pointer so that I can spawn new async task from within the handler of the previous task without having to worry about the resources getting deleted in the middle of my work.

The problems start when I tried to subclass my client to handle different pages in different ways. The compiler complains that the type of the shared_ptr doesn't match the type of this.

Does anybody know how this is solved? I haven't been able to figure it out by myself.


Solution

  • This is unrelated to Asio.

    If you inherited a base class from enable_shared_from_this, but need it in the derived one, use boost::static_pointer_cast:

    struct base : enable_shared_from_this<base>
    {
    };
    
    struct derived : base
    {
      shared_ptr<derived> shared_from_derived()
      {
        return static_pointer_cast<derived>(shared_from_this());
      }
    };