In C ++, how to write a destructor to free the memory of a pointer to a structure?

Here is my structure a

struct A { int a1; int a2; ~A() { } }; 

B is another structure containing 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 I use below code

 int bb1; vector <A*> aa1; // do some stuff B *ptrB = new B(bb1, aa1); 

I need to remove / free all the memory ptrB points to. Therefore, I need to write the correct destructor inside struct B. How do I cross each element that A points to and delete them?

+6
source share
3 answers

If you are using the C ++ 11 compiler, just use std :: shared_ptr and you do not need to worry about deleting. This is because shared_ptr is a smart pointer that automatically deletes what it points 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 generic pointer whenever you highlight 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 is more information on the topic of smart pointers.

I should also note that if you don't have a C ++ 11 compiler, you can get generic pointers from the BOOST library .

+12
source

You only need delete objects allocated by new . In this case, there is no need to delete b1 , since it was not dynamically allocated. Moreover, if you did not initialize ptr2a dynamic memory, the deletion was undefined.

Therefore, there is no need to worry about deleting A data, since it will be deleted from memory along the class instance.

+5
source

You have only one pointer to A Therefore, you only need to remove this:

 ~B() { delete ptr2A; } 

Note that you cannot delete b1, as this is a simple int ! (The memory occupied by the structure variables, for example b1 and the ptr2A pointer ptr2A (and not what it points to), is automatically destroyed along with any instances of this structure.)

+4
source

All Articles