First, you store the original pointers in your vector. These pointers are just pointers. They can point anywhere. They can point to local objects that cannot be deleted with delete . And even if they point to dynamically created objects, this does not necessarily mean that the user wants them to die with the vector. How should a vector know all this?
This is a matter of ownership of objects. The owner of the property is responsible for its proper and timely removal. Regular source pointers do not express ownership. This is why the vector cannot make any assumptions about whether to delete objects or not. If you want to tell the vector that it owns its dynamic objects, use the appropriate smart pointers.
Secondly, note that your removal method is not necessarily safe in the general case. Some standard containers assume that the data stored in them is always valid. When you delete for each vector element, the data in the vector becomes "invalid" (pointers become undefined). This is normal with a vector. But doing something like this in a βsmarterβ container, for example, std::map or std::unordered_set , for example, may lead to problems. Even if you immediately destroy the container itself, it is quite possible that the algorithm for destroying the container may require analysis (comparison, hash, etc.) of the values ββof individual elements. And you just killed them all with your cycle.
Reasonable pointers naturally resolve this issue. But if you need to use the delete guide for raw pointers stored in a standard container, then it would be better to follow these steps:
- Get the value of an element in
i and store it in the pointer p - Remove item from
i from container - Do
delete p
In the end, you will get an empty container and delete d data. Again, your approach will work for simple sequences like std::vector or std::list , but don't do this with ordered or hashed ones.
source share