Boost logo

Boost Users :

From: Joaquin M López Muñoz (joaquinlopezmunoz_at_[hidden])
Date: 2021-09-09 11:16:45


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 list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net