Home > Article > Backend Development > Does `vector::erase()` Destroy Objects in a Vector of Pointers?
Does Vector::Erase Destroy Objects in a Vector of Pointers?
When dealing with vectors containing object pointers, erasing an element using vector::erase() raises concerns about the fate of the pointed-to objects. While vector::erase() removes the element from the vector, it does not automatically destroy the actual object.
Behavior of Vector::Erase
Vector::erase() removes the element from the vector but does not take ownership of destroying the object. However, if the contained object is a raw pointer, vector::erase() does not call its destructor before removal.
Handling Raw Pointers
To ensure proper resource management, you must explicitly delete each contained pointer to delete the objects they point to. This can be achieved using a loop:
<code class="cpp">void clearVectorContents(std::vector<YourClass *> &a) { for (int i = 0; i < a.size(); i++) { delete a[i]; } a.clear(); }
Avoiding Raw Pointers
Storing raw pointers in standard containers is generally discouraged. For objects allocated dynamically, consider using smart pointers like boost::shared_ptr to handle memory management.
Generic and Elegant Solution
A more elegant solution utilizes templates and the for_each algorithm:
<code class="cpp">// Functor for deleting pointers in vector template<class T> class DeleteVector { public: void operator()(T x) const { delete x; } };</code>
This functor can be used with for_each to delete pointers in a vector:
<code class="cpp">for_each(myclassVector.begin(), myclassVector.end(), DeleteVector<myclass *>());</code>
Example Usage
Consider a vector of pointers to myclass objects. The following code allocates, prints, and deletes the objects:
<code class="cpp">#include <iostream> #include <vector> #include <algorithm> #include <functional> class myclass { public: int i; myclass(): i(10) {} }; // Functor for deleting pointers in vector template<class T> class DeleteVector { public: void operator()(T x) const { delete x; } }; int main() { // Vector of myclass pointers std::vector<myclass *> myclassVector; // Add objects to the vector for (int i = 0; i < 10; i++) { myclassVector.push_back(new myclass); } // Print object values for (int i = 0; i < myclassVector.size(); i++) { std::cout << " " << (myclassVector[i])->i; } // Delete objects using functor and for_each for_each(myclassVector.begin(), myclassVector.end(), DeleteVector<myclass *>()); // Clear the vector myclassVector.clear(); // Print the empty vector size std::cout << "\n" << myclassVector.size(); return 0; }</code>
The above is the detailed content of Does `vector::erase()` Destroy Objects in a Vector of Pointers?. For more information, please follow other related articles on the PHP Chinese website!