I have a quick question on the implications of returning a pointer to a vector or map of pointers from a public member function in a class.
Here is my code:
here is a member function in class B
vector<A*>* ClassB::getfunction(){
returns m_test;
}
m_test is a private data member of class B of type pointer to a vector of pointers. This object would be initialized on the heap so I would need to delete it in the class destructor (including all the elements in the vector).
I would then use the function as shown below.
B* ex_B = new B();
vector<A*>* ex_ptr_vecA = new vector<A*>;
ex_ptr_vecA = ex_B->getfunction();
My question:
Since I have two objects that’s memory is both allocated on the heap will I need to delete them both?
Does the order matter and would the following be correct?
B* ex_B = new B();
vector<A*>* ex_ptr_vecA = new vector<A*>;
ex_ptr_vecA = ex_B->getfunction();
//do something with ex_ptr_vecA
//Then I want to delete the allocate memory to the heap
//delete class B first
delete ex_B;
//and then the vector
//need to loop over vector elements and delete one at a time
for(int i =0; i < ex_ptr_vecA; i++){
delete ex_ptr_vecA->at(i);
}
delete ex_ptr_vecA;
Would this be correct or would I be trying to delete dangling pointers because the destructor of class B has already de-allocated the heap memory?
Here you allocated 2 blocks of memory and stored the adress of the beginning of those blocks in corresponding pointer variables. All fine.
Now you’ve reassigned ex_ptr_vecA with whatever address
getfunction()returns. You no longer hold the address that newvector<A*>returned, you can’t free it anymore, hence you’ve got a memory leak.If you only need the pointer to
ex_B‘s internalvector<A*>then simply say this:The way you showed in your example code
ex_ptr_vecApoints to the same vector that you’ve allocated inex_Bclass. Ifex_Bdeletes that internal vector in it’s destructor, thendelete ex_ptr_vecA;means you’re deleting twice – that’s undefined behaviour.