I’m currently getting myself into c++ for lower level coding with opengl. I come from a heavy objc background so I have some understanding about memory management but I can’t seem to get how the “boost” library manages container types like ptr_vector.
I think my problem is related to the fact that I have no idea how ptr_vector manages the destruction of itself and its objects.
Please take a look at the following code:
// Header file
...
ptr_vector<IObject3D> objects;
...
// Implementation file
...
void ApplicationEngine::init()
{
WavefrontObject3D *object = new WavefrontObject3D("Ninja.obj");
objects.push_back(object);
}
...
So, for the actually question: am I creating a leak here through the “object” variable?
I’m used to retain and release my objects manually with explicit calls in objc:
previously I had to alloc init the WavefrontObject3D object, add it to an array and afterwards release that same object to avoid leaks.
But when I add a delete object after the push_back call the deconstructor of the WavefrontObject3D object is called. This gives me a hint that the ptr_vector isn’t retaining the object variable. Is my assumption correct?
Additional, but related, question: let’s say I want to destroy the containing class ApplicationEngine don’t I have to call some kind of deconstructor on the ptr_vector or the elements it manages?
No, this doesn’t create a leak. All
ptr_*containers will delete objects that are stored in them when the container goes out of scope.If you delete the object after adding it to the container, you will create
undefined behavioras the container will attempt to delete it again.Additional question: No, if you store the
ptr_vectorby value its lifetime is managed by the scope of the surrounding class.Let’s write a simple implementation of
ptr_vector. It has no support for indirect iterators and custom deleters and a lot of other things but shows the principles used.If user class goes out of scope, the destructor of
ptr_vectorwillbe called and all memory will be reclaimed. No leak in sight.