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

前端 未结 10 833
失恋的感觉
失恋的感觉 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:13

    Are you sure that memory allocation is the bottleneck you think it is? Is B's constructor trivially fast?

    If memory allocation is the real problem, then placement new or some of the other solutions here might well help.

    If the types and ranges of the param[1..4] are reasonable, and the B constructor "heavy", you might also consider using a cached set of B. This presumes you are actually allowed to have more than one at a time, that it does not front a resource for example.

提交回复
热议问题