C++ returning a vector/map of pointers from a public member function
<p>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.</p>

<p>Here is my code:</p>

<p>here is a member function in class B</p>

<pre><code>vector&lt;A*&gt;* ClassB::getfunction(){
    returns m_test;
}
</code></pre>

<p>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).</p>

<p>I would then use the function as shown below.</p>

<pre><code>B* ex_B = new B();

vector&lt;A*&gt;* ex_ptr_vecA = new vector&lt;A*&gt;;  

ex_ptr_vecA = ex_B-&gt;getfunction();
</code></pre>

<p>My question: </p>

<p>Since I have two objects that's memory is both allocated on the heap will I need to delete them both? </p>

<p>Does the order matter and would the following be correct? </p>

<pre><code>B* ex_B = new B();

vector&lt;A*&gt;* ex_ptr_vecA = new vector&lt;A*&gt;;  

ex_ptr_vecA = ex_B-&gt;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 &lt; ex_ptr_vecA; i++){
     delete ex_ptr_vecA-&gt;at(i);
}

delete ex_ptr_vecA;
</code></pre>

<p>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?</p>
