Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to call std::vector.clear() before assigning using operator=?

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?

like image 942
aerobot Avatar asked May 10 '26 03:05

aerobot


2 Answers

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]

like image 106
David Rodríguez - dribeas Avatar answered May 12 '26 17:05

David Rodríguez - dribeas


MsgUnit has 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.

like image 44
Mike Seymour Avatar answered May 12 '26 16:05

Mike Seymour