himmel February 2016

release dynamic memory for pointer member in c++

I have a class:

class A {
    A();
    ////////something about the class A
};

then I have another class:

class B {
public:
    B();
    A* member_a;
};
B::B()
{
    this->member_a = new A();
}

what I want to do is like this:

main()
{
    vector<B> vec_b;
    int num=1;
    while(some_condition)
    {
        for (int i=0; i<num; i++)
        {
            vec_b.pushback(B());
        }
        ////////do something about vec_b;
        num++;
    }
}

I know I am facing a memory leak issue because of the new A() in the constructor of class B. So I am trying to get help to release the memory after each while loop, which means to recycle all the memory that has been taken by the vec_b and all the objects of class B in the vector, the most important is to release the memory taken by class-A-objects. Thank you very much!

Answers


CoryKramer February 2016

That seems like it should be the job of B's destructor

B::~B()
{
    delete member_a;
}

If you have access to C++11 or later, I would prefer std::unique_ptr so you get this deallocation for free

class B {
public:
    B();
    std::unique_ptr<A> member_a;
};

B::B()
{
    member_a = std::make_unique<A>();
}


evk1206 February 2016

Write the delete in the destructor of class b

B::~B
{
delete member_a;
}

Post Status

Asked in February 2016
Viewed 3,621 times
Voted 13
Answered 2 times

Search




Leave an answer