Need to call std::vector.clear() before assigning using operator=?
c++, memory-leaks, stdvector, vector
Solution
No, assignment will make the destination vector value-equivalent to the source vector. It will internally do what it needs to ensure this without leaking. [Assuming that the copy-constructor, assignment and destructors of your type don't leak]
Problem
I profiled my code recently with Visual Leak Detector for the first time, and it indicated a leak in a vector, which I wasn't expecting. The code is like so: ``` void func() { std::vector<MsgUnit> msgVec; do { // msgVec.clear(); // do I need to do this to avoid a leak? msgVec = m_obj->returnMsgUnitVector(); } while (someConditionNotMet); // process msgVec return; } ``` `MsgUnit` has a copy constructor and destructor. I haven't found the time to do in-depth testing, but a quick fix seems to indicate that uncommenting the `clear()` method removes the leak. I'm wondering what the standard says about this behaviour. Do I need to clear the vector before assigning to it, to avoid a leak?