Standard STL containers place a copy of the source object in the container using the copy constructor. When a container is destroyed, the destructor of each object in the container is also called to safely destroy the object.
Pointers are treated the same way. The thing about pointers is POD data. A copy constructor for a pointer is just a copy of the address, and the POD data does not have a destructor. If you want the container to control the pointer, you need to:
- Use a smart pointer container. (e.g., a generic pointer).
- Use the ppt boost container.
I prefer container pointer:
The pointer containers are the same as the STL containers, except that you put pointers in them, but then the container becomes the property of the object that the pointer points to, and thus frees the object (usually by deleting it) when the container is destroyed.
When you access the members of the ptr container, they are returned via the link, so they behave exactly like a standard container for use in standard algorithms.
int main() { boost::ptr_vector<int> data; data.push_back(new int(5)); data.push_back(new int(6)); std::cout << data[0] << "\n";
It should also be noted that smart pointers in a container are a valid alternative, unfortunately std :: auto_ptr <> is not a valid smart pointer choice for this situation.
This is because the STL containers assume that the objects they contain can be copied, unfortunately std :: auto_ptr <> cannot be copied in the traditional sense, since it destroys the original value on the copy, and therefore copy source cannot be Set.
source share