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

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

    I'd go with boost::scoped_ptr here:

    class A: boost::noncopyable
    {
        typedef boost::scoped_ptr b_ptr;
        b_ptr pb_;
    
    public:
    
        A() : pb_() {}
    
        void calledVeryOften( /*…*/ )
        {
            pb_.reset( new B( params )); // old instance deallocated
            // safely use *pb_ as reference to instance of B
        }
    };
    

    No need for hand-crafted destructor, A is non-copyable, as it should be in your original code, not to leak memory on copy/assignment.

    I'd suggest to re-think the design though if you need to re-allocate some inner state object very often. Look into Flyweight and State patterns.

提交回复
热议问题