I have a class that creates a vector of objects. In the deconstructor for this class I\'m trying to deallocate the memory assigned to the objects. I\'m trying to do this by
In C++, you can only delete data by pointer. You've accomplished this using the & operator, but if your vector doesn't contain pointers that point to memory allocated on the machines heap (not the stack, as is the method when you have a normal variable declaration) then you can TRY to delete it, but you will encounter undefined behavior (which will hopefully cause a program crash).
When you insert into a vector, the vector calls the class's copy constructor and you're actually inserting a copy of the object. If you have a function whose sole purpose is like the following:
void insertObj(obj & myObject) { myVector.insert(myObject); }
Then realize that there are two obj's in this scope: the one you passed in by reference, and the copy in the vector. If instead we had pass in myObject by value and not by reference, then we could say that two copies of the object exist in this scope, and one exists in the caller. In each of these 3 instances, they are not the same object.
If you are instead storing pointers in the container, then the vector will create a copy of the pointer (NOT a copy of the object) and will insert the copied pointer into the vector. It is usually not a good practice to insert elements into a container by pointer unless you know that the object will live at least until the container is done with it. For example,
void insert() { Obj myObj; myVector.insert(&myObj); }
Is probably a very bad idea, as you'd have a pointer in the vector that points to an object that is destroyed automatically when it goes out of scope!
Point being, if you malloc'd or new'd your object, then you need to free or delete it. If you created it on the stack, then do nothing. The vector will take care of it when it is destroyed.
For a deeper understanding of stack-based allocation vs. heap-based allocation, see my answer here: How does automatic memory allocation actually work in C++?