使用std :: swap在C ++函数中发生内存泄漏

时间:2013-07-21 23:37:54

标签: c++ qt memory-leaks

我正在使用qt creator而我遇到内存泄漏问题。我已经阅读了一些关于动态内存分配的帖子,但从我所看到的,我无法理解为什么我的函数在内存中积累了一些东西。

我完全确定我已经确定了导致问​​题的功能:

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]);

}

我是一个新手,但据我所知,函数内部创建的对象应该在完成后销毁。如果有人能告诉我为什么这个功能导致内存泄漏,我提前感谢你。

1 个答案:

答案 0 :(得分:0)

我看到的方式有三种可能性:

1 :(最有可能)CNet析构函数没有正确地解除分配由其构造函数保留的内存。

要检查这一点,请使用全局CNet newNet变量,并且不要在每次进入此例程时重新创建临时变量(而只是设置全局newNet变量的值),所以你不要继续调用构造函数/析构函数。

2:std::swap(newNet, netVector[destination]);调用,我认为这会创建一个临时变量,如下所述:

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

尝试评论std::swap电话,看看会发生什么。

3:for循环中的某些内容很可疑,但是你没有提供详细信息。

祝你好运。