Here's my structure A
struct A {
int a1;
int a2;
~A() { }
};
B
is another structure that contains a pointer to A
struct B {
B(int b, A* a)
: b1(b), ptr2A(a)
{}
int b1;
A* ptr2A;
~B() {
delete b1;
// traverse each element pointed to by A, delete them <----
}
};
Later on I use below code
int bb1;
vector <A*> aa1;
// do some stuff
B *ptrB = new B(bb1, aa1);
I need to delete/free all the memory pointed to by ptrB. Hence I need to write correct destructor inside struct B. How do I traverse each element pointed to by A and delete them?
Destructor frees the memory allocated to the object of the class only when the object goes out of the scope. Free function frees the memory allocated to the object/ dynamically allocated variables whenever the function is called with respect to the object/dynamically allocated variable.
A destructor only destroys and cleans up the object. It does not deallocate the memory.
When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.
It destroys the object that's pointed to (using its destructor, if it has one, and doing nothing otherwise), and deallocates the memory that's pointed to.
You've only got one pointer to A
. So you only need to delete that:
~B() {
delete ptr2A;
}
Note that you can't delete
b1, since it's a plain int
! (The memory taken up by the variables of the structure, such as b1
and the pointer ptr2A
itself (not what it points to) are destroyed automatically along with any instances of that structure.)
You need only to delete
objects allocated by new
. In this case there's no need to delete b1
as it has not been dynamically-allocated. Moreover, if you did not initialize ptr2a
with dynamic memory, deleting it is undefined behavior.
So there's no need to worry about deleting A
s data as it will be destructed from memory along wih the instance of the class.
If you're using a C++11 compiler, just use std::shared_ptr and you don't have to worry about deletes. This is because the shared_ptr is a "smart" pointer that will automatically delete what its pointing to.
#include <memory>
struct B
{
int b1;
std::shared_ptr<A> ptr2A;
B(int b, std::shared_ptr<A> a):b1(b),ptr2A(a)({}
~B(){} //look ma! no deletes!
};
Use a shared pointer whenever you allocate something:
#include<memory>
...
{
....
std::shared_ptr<B> ptrB( new B(bb1, aa1) );
//Here is another, more readable way of doing the same thing:
//auto ptrB = std::make_shared<B>(bb1,aa1);
...
}
//no memory leaks here, because B is automatically destroyed
Here's more info on the subject of smart pointers.
I should also mention that if you don't have a C++11 compiler, you can get shared pointers from the BOOST library.
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