I have a class A with a member which is a vector of object pointers of another class B
class A
{
std::vector<B*> m_member_A
m_member_A is populated by creating objects of B by using new operator
B* b1 = new B;
m_member_A.push_back(b1);
In A's destructor, is the following correct to free up everything?
A::~A()
{
for(int i = 0; i < m_member_A.size(); ++i)
{
delete m_member_A[i];
}
m_member_A.clear();
}
It's correct, as long as you also have a correct copy constructor and copy-assignment operator per the Rule of Three. Note that the clear() is redundant, since the vector's destructor will release its memory.
By why are you messing around with pointers and new? Why not follow the Rule of Zero, and use vector<B>, or vector<unique_ptr<B>> if you need pointers for polymorphism? Then you shouldn't need to worry about a destructor, copy constructor or copy-assignment operator at all; and you'll get move semantics as a bonus.
Yes, it's correct… yet it is not sufficient.
You will also need to deep-copy the container whenever your A is copied.
If you can use smart pointers inside the vector, then so much the better. Just be clear in your mind and in your code about who owns what.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With