El 09/09/2021 a las 11:28, John Emmas via Boost-users escribió:
On 08/09/2021 15:56, John Emmas wrote:

I realise there are two types of hook available for 'boost::intrusive::list' ( the list_member_hook<> and the list_base_hook<>) - so are there certain situations where one would preferable over the other?


Overnight I got told (off-list) that when 2 x classes are both declared using the 'list_base_hook<>' option, I'll get a runtime crash if I try to add the same object to both lists.  In other words, this will crash at the specified line:-

    class animal : public boost::intrusive::list_base_hook<>
    {
       [...]
    };

[...]

       animals.push_back (a2);  // <--- 'bulldog' works okay
[...]
       dogs.push_back (a2);     // <--- 'bulldog' crashes !!!

You're trying to insert a2 into dogs when the element is alredy inserted into animals.
You can either remove a2 from animals beforehand:

   animals.erase(Animals::s_iterator_to(a2));

or, if you mean for the elements to be allowed in both lists at the same time, use tags:

    #include <boost/intrusive/list.hpp>
    #include <string>
    #include <utility>

    typedef boost::intrusive::list_base_hook<boost::intrusive::tag<struct animal_tag>> animals_hook;     typedef boost::intrusive::list_base_hook<boost::intrusive::tag<struct dog_tag>> dogs_hook;

    class animal :
      public animals_hook, public dogs_hook
    {
     public:
        animal (std::string n, int l) : name{std::move(n)}, legs{l} {}

        std::string name;
        int legs;
    };

    typedef boost::intrusive::list<animal,boost::intrusive::base_hook<animals_hook>> Animals;     typedef boost::intrusive::list<animal,boost::intrusive::base_hook<dogs_hook>> Dogs;

    int main()
    {
        animal a1{"labrador", 4};
        animal a2{"bulldog", 4};

        Animals animals;
        animals.push_back (a2);  // <--- 'bulldog' works okay

        Dogs dogs;
        dogs.push_back (a1);     // <--- 'labrador' works okay
        dogs.push_back (a2);     // <--- 'bulldog' works okay

        return 0;
    }

Joaquín M López Muñoz


_______________________________________________
Boost-users mailing list
Boost-users@lists.boost.org
https://lists.boost.org/mailman/listinfo.cgi/boost-users

Reply via email to