Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 动态分配的std::vector似乎存在内存泄漏_C++_Stl_Memory Leaks_Vector - Fatal编程技术网

C++ 动态分配的std::vector似乎存在内存泄漏

C++ 动态分配的std::vector似乎存在内存泄漏,c++,stl,memory-leaks,vector,C++,Stl,Memory Leaks,Vector,感谢大家,在整个项目中再次检查后,真正的问题是缺少虚拟析构函数。。。。导致内存泄漏的原因 #include "stdafx.h" #include <vector> class VecContainerParent { public: VecContainerParent(){}; 它会导致内存泄漏 良好(因为未使用ptr): 这很典型。当你 a = new VecContainerChild(); delete a; 如果通过指向基类子对象的指针删除

感谢大家,在整个项目中再次检查后,真正的问题是缺少虚拟析构函数。。。。导致内存泄漏的原因

#include "stdafx.h"
#include <vector>

class VecContainerParent
{
public:
    VecContainerParent(){};
它会导致内存泄漏

  • 良好(因为未使用ptr):


  • 这很典型。当你

       a = new VecContainerChild();
        delete a;
    
    如果通过指向基类子对象的指针删除对象,则调用未定义的行为,除非基类具有虚拟析构函数。基本上,在这种情况下,孩子的析构函数不会运行


    两个代码段中都没有内存泄漏。。。。除非您将默认的
    操作员新建
    和/或
    操作员删除
    替换为有缺陷的版本。您能提供一些证据证明这是内存泄漏吗?这里没有明显的泄漏。此外,如果内存管理器在案例1中每次循环时都不重用相同的内存,那么它可能看起来像是在“泄漏”内存,因为越来越多的物理RAM将分配给进程的虚拟地址空间,因此像
    top
    这样的工具将显示内存使用量的增加。不过,这只是一个幻影;一旦其他东西需要它,它就会被回收。不能保证
    delete
    会将内存释放回操作系统;小的分配通常保存在堆中以供重用。但我当然希望代码片段1只分配少量内存,然后重用它;如果使用量持续增加,那么就有可疑的事情发生了。
    };
    
    class VecContainerChild : public VecContainerParent
    {
    public:
        VecContainerChild(){};
    
        //virtual ~VecContainerChild(){};
    private:
        std::vector<int> vec;
    };
    
    ////////// WITH MEMORY LEAK ///////////////
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        VecContainerParent *a;
        while(true)
        {
            a = new VecContainerChild();
            delete a;
        }
    } 
    
    class VecContainer
    {
    public:
           VecContainer(){};
    private:
           std::vector<int> vec;
    }
    
    int main()
    {
        VecContainer *a;
        while(true)
        {
            a = new VecContainer();
            delete a;
        }
    }
    
    int main()
    {
        while(true)
        {
            VecContainer a;
        }
    }
    
       a = new VecContainerChild();
        delete a;