How to prevent destructors from being called on objects managed by boost::fast_pool_allocator?

后端 未结 3 566
伪装坚强ぢ
伪装坚强ぢ 2021-01-06 09:33

I would like to take advantage of the following advertised feature of boost::fast_pool_allocator (see the Boost documentation for Boost Pool):

3条回答
  •  广开言路
    2021-01-06 10:03

    The answer to this question is contained in the comments beneath @qehgt's answer, and in detail in this new question.

    Namely:

    There is a clear and formal distinction between two related aspects of object instantiation and deletion:

    • (1) Allocation and deallocation of memory

    • (2) Calling of constructors and destructors

    The purpose of a custom allocator is (1) only.

    The container objects handle (2), and they call functions in the custom allocator to determine the location of memory in which to construct the object, and to tell the custom allocator that it's OK to free the allocated memory for given objects. But the calls to the constructor/destructor themselves are made by the container, not by the custom allocator.

    Therefore, the way to achieve the goal of this question is the following: Declare the container object via new and NEVER CALL delete on it (but use the custom allocator to guarantee that the objects you later create in the container are stored in the memory pool, and then manually free the memory pool yourself by calling purge_memory()):

    class Obj { // has operator<() for use with std::set };
    
    typedef std::set, boost::fast_pool_allocator> fast_set_obj;
    
    // Deliberately do not use a managed pointer -
    // I will *NOT* delete this object, but instead
    // I will manage the memory using the memory pool!!!
    fast_set_obj * mset = new fast_set_obj;
    
    // ... add some Obj's to 'mset'
    mset->insert(Obj());
    mset->insert(Obj());
    
    // Do something desireable with the set ...
    ...
    
    // All done.
    // It's time to release the memory, but do NOT call any Obj destructors.
    // The following line of code works exactly as intended.
    
    boost::singleton_pool::purge_memory();
    

    (The above code is taken from the linked question, above.)

    However, I am still having an issue, not directly related to the intention behind this current question: The code above does not work if a map is used instead of a set. See the linked question for details.

提交回复
热议问题