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?
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]
MsgUnithas a copy constructor and destructor.
I guess it doesn't have an copy-assignment operator (per the Rule of Three), which is why you get leaks or worse when you reassign them. The implicitly-generated operator will simply assign each class member. If some of those members are dumb pointers to manually-managed resources, then you'll lose those pointers and leak the resources.
Either implement that or, better still, redesign MsgUnit to use a smart pointer (or similar) to manage its dynamic resources automatically with no need for you to mess around with destructors and the like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With