简体   繁体   中英

C++ Boost Intrusive List - Example

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM