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

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

    Erm, is there some reason you can't do this?

    A() : b(new B()) { }
    
    void calledVeryOften(…) 
    {
        b->setValues(param1, param2, param3, param4); 
    }
    

    (or set them individually, since you don't have access to the B class - those values do have mutator-methods, right?)

提交回复
热议问题