C++ Boost Intrusive List - Example

1.6k views Asked by At

I am curious about the boost intrusive containers and wanted to test it. I basically copy pasted the example from boost.org in the chapter "How to use Boost.Intrusive". So my Code looks like this:

#include <iostream>
#include <boost/intrusive/list.hpp>

using namespace boost::intrusive;

struct test_tag1;
struct test_tag2;

typedef list_base_hook< tag<test_tag1> > BaseHook;
typedef list_base_hook< tag<test_tag2> > BaseHook2;

class TestClass : public BaseHook, public BaseHook2 {
    public:
        int test_var;
};

typedef list< TestClass, base_hook<BaseHook> > class_list;
typedef list< TestClass, base_hook<BaseHook2> > class_list2;

int main() {
    class_list list;

    TestClass class1 = TestClass();
    list.push_back(class1);

    bool is_the_same = (&list.front() == &class1);
    std::cout << is_the_same;

    return 0;    
}

It compiles successfully, but on execution I keep getting the following error:

1Assertion failed: !hook.is_linked(), file boost/intrusive/detail/generic_hook.hpp, line 47

I opened the generic_hook.hpp to check what raises this error, and the description of the assert is:

void destructor_impl(Hook &hook, detail::link_dispatch<safe_link>)
{  //If this assertion raises, you might have destroyed an object
   //while it was still inserted in a container that is alive.
   //If so, remove the object from the container before destroying it.
   (void)hook; BOOST_INTRUSIVE_SAFE_HOOK_DESTRUCTOR_ASSERT(!hook.is_linked());
}

But that cant be true, at least I cant see where I could have destroyed the object accidently. I dont know all the details about these containers yet, so I would be gratefull to get some help here.

1

There are 1 answers

1
walnut On BEST ANSWER

You declared class1 after list. So when main exits, class1 is destroyed before list is. (Destruction in reverse order of construction.)

You have inserted class1 into list. So when list is destroyed, class1, which is still inserted into the container, is not alive anymore.

Move the declaration of class1 before that of list, so that it will be destroyed later.

Compare also to the boost documentation from which you probably constructed the code in your question. There the element object is also declared before the list.

In general the note at the bottom of the linked documentation page is important. It says that the container only stores a reference and that you must make sure that the inserted elements stay alive longer than the container.