Alex Alex - 1 month ago 5
C++ Question

C++ vector on heap instead of stack

I have come across an interesting problem. I have a function in C++ that returns a vector full of classes. Once the vector is returned it calls deconstrustors for each class that is element in the vector. The problem is an obvious one, that the data is destroyed where class points to the pointers which get released when object is destroyed. I can only assume the deconstructors are called because vector is on the stack not on the heap.

So the question is: Is there anyway to keep returning vector from a function, without it being destroyed? Or would I have to either pass a pointer to return vector as an input to the function.

Alex

Answer

You can create anything on heap with new. You shouldn't give out from the function the references to your stack objects, as they will be destroyed as soon as the function finishes.

If you prefer your function to return the vector by value, be sure that the objects inside the vector implement copy constructor (and perhaps assignment operator, too, not sure about that). Having that, please do not forget about the Rule of Three.