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

前端 未结 10 872
失恋的感觉
失恋的感觉 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条回答
  •  春和景丽
    2021-02-07 19:10

    How about allocating the memory for B once (or for it's biggest possible variant) and using placement new?

    A would store char memB[sizeof(BiggestB)]; and a B*. Sure, you'd need to manually call the destructors, but no memory would be allocated/deallocated.

       void* p = memB;
       B* b = new(p) SomeB();
       ...
       b->~B();   // explicit destructor call when needed.
    

提交回复
热议问题