How to avoid successive deallocations/allocations in C++?

前端 未结 10 889
失恋的感觉
失恋的感觉 2021-02-07 18:26

Consider the following code:

class A
{
    B* b; // an A object owns a B object

    A() : b(NULL) { } // we don\'t know what b will be when constructing A

             


        
10条回答
  •  猫巷女王i
    2021-02-07 18:54

    Simply reserve the memory required for b (via a pool or by hand) and reuse it each time you delete/new instead of reallocating each time.

    Example :

    class A
    {
        B* b; // an A object owns a B object
        bool initialized;
    public:
        A() : b( malloc( sizeof(B) ) ), initialized(false) { } // We reserve memory for b
        ~A() { if(initialized) destroy(); free(b); } // release memory only once we don't use it anymore
    
        void calledVeryOften(…)
        {
            if (initialized)
                destroy();
    
            create();
        }
    
     private:
    
        void destroy() { b->~B(); initialized = false; } // hand call to the destructor
        void create( param1, param2, param3, param4 )
        {
            b = new (b) B( param1, param2, param3, param4 ); // in place new : only construct, don't allocate but use the memory that the provided pointer point to
            initialized = true;
        }
    
    };
    

    In some cases a Pool or ObjectPool could be a better implementation of the same idea.

    The construction/destruction cost will then only be dependante on the constructor and destructor of the B class.

提交回复
热议问题