c++boostevent-handlingshared-ptrintrusive-containers

Boost::IntrusiveList with Shared Pointers


So I'm writing an event handling system using FastDelegate<> and the boost library. I need to setup a Queue of shared pointers to event data as well as a list of FastDelegate> for listeners. So here's the problem.

Intrusive list and queue don't allow shared_ptr or even constant references which makes my code cause compile time errors. Anyway that I can do this?

It seems safest to hand off a shared ptr to delegates that way the event stays around until everyone is truly done with it.


Solution

  • Q. Intrusive list and queue don't allow shared_ptr

    No problem:

    Live On Coliru

    #include <boost/intrusive/list.hpp>
    #include <boost/shared_ptr.hpp>
    
    struct Event {};
    
    struct Node : boost::intrusive::list_base_hook<> {
        boost::shared_ptr<Event> event { new Event };
    };
    
    typedef boost::intrusive::list<Node> event_list;
    
    int main() {
        std::vector<Node> nodes(10);
    
        event_list pending;
        pending.push_back(nodes[3]);
        pending.push_back(nodes[7]);
    }
    

    From the fact that you expected (?) intrusive::list<T> to work for T = shared_ptr<...> tells me that you want a simple std::list (or just a std::vector) instead.

    or even constant references

    Constant references are no problem either. Did you want to use shared_ptr<const Event>? Because that's a good option if you're sharing the event with multiple parties.