简体   繁体   中英

Memory leak in C++ function using std::swap

I'm using qt creator and I'm having trouble with a memory leak. I've read some posts about dynamic memory allocation but from what I've seen, I can't understand why my function is accumulating something in memory.

I'm completely sure I've pinpointed the function that causes the problem:

void CSimWindow::cloneNet(int origin, int destination)

    int newNumSensors = netVector[origin].getNumSensors();
    int newNumActuators = netVector[origin].getNumActuators();
    int newNumNeurons = netVector[origin].getNumNeurons();

    CNet newNet(newNumNeurons, 0);
    newNet.setNumSensors(newNumSensors);
    newNet.setNumActuators(newNumActuators);

    for (int i = 0; i < netVector[origin].getNumNeurons(); i++)
    {
        ...
    }
    std::swap(newNet, netVector[destination]);

}

I'm quite a newbie, but as I understand it, the objects created inside the function should be destroyed when it's finished. If anyone can tell me why this function causes the memory leak, I thank you in advance.

The way I see it there are three possibilities:

1: (the most likely) the CNet destructor does not properly de-allocate memory that is reserved by its constructor.

To check that, use a global CNet newNet variable, and do not re-create temporary variables every time you go into this routine (rather just set the values of the global newNet variable), so you do not keep calling the constructor/destructor.

2: The std::swap(newNet, netVector[destination]); call, which I think creates a temporary variable as explained here:

http://www.cplusplus.com/reference/algorithm/swap/

Try to comment the std::swap call and see what happens.

3: Something inside the for loop is fishy, but you do not provide details there.

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM