C++ C++;向量和内存泄漏

C++ C++;向量和内存泄漏,c++,memory-leaks,std,C++,Memory Leaks,Std,我以前在某个地方读到,向量会导致内存泄漏,这取决于它们的使用方式,但我想问一下,只是为了确保: #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> int main() { vector<somePtr*> listPtrs; return 0; //Detects memory leaks } \define\u CRTDBG\u MAP\u ALL

我以前在某个地方读到,向量会导致内存泄漏,这取决于它们的使用方式,但我想问一下,只是为了确保:

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

int main()
{
    vector<somePtr*> listPtrs;

    return 0;
    //Detects memory leaks
}
\define\u CRTDBG\u MAP\u ALLOC
#包括
#包括
int main()
{
向量列表;
返回0;
//检测内存泄漏
}
这并没有检测到任何东西:

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

int main()
{
    {
        vector<somePtr*> listPtrs;
    }

    return 0;
    //No memory leaks detected
}
\define\u CRTDBG\u MAP\u ALLOC
#包括
#包括
int main()
{
{
向量列表;
}
返回0;
//未检测到内存泄漏
}
在清除指针之前,将从向量中删除对象。 我想我记得读到向量、列表和其他std容器在它们所在的块之后会自动删除,所以在示例1中,我得到内存泄漏,因为内存泄漏函数在块结束之前被调用,所以向量仍然存在并导致它

不过我不确定,我想我读这篇文章已经有一段时间了,我只能找到关于对象没有被删除,只是指针被删除的问题


这是真的吗?如果我使用包含向量和列表的全局类,会不会出现内存泄漏?

在堆栈上分配向量的两段代码中。因此,向量的析构函数在超出范围时将被调用。我不知道你们用的是什么检漏仪,但若它在主出口前检查是否有泄漏,它可能确实检测到了泄漏,但实际上并不是泄漏


遇到内存泄漏问题的地方是
std::vector
析构函数不会对向量中的项调用
delete
,尽管它会调用它们的析构函数。因此,
vector
vector
是很好的,因为向量持有实际对象并将调用它的析构函数。另一方面,如果你有
向量
,你需要小心;删除向量不会释放与其指向的
MyClass
对象相关的内存。

调用
\u CrtDumpMemoryLeaks
的点很重要,因为所有使用的内存可能尚未释放。例如,在下面的示例中,如果在
listPtrs
超出范围之前调用
\u CrtDumpMemoryLeaks()
,则它分配的任何内存都将包含在泄漏内存列表中

#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <vector>

int main()
{
    std::vector<struct Foo*> listPtrs;

    _CrtDumpMemoryLeaks();

    return 0;
}
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <vector>

int main()
{
    {
        std::vector<struct Foo*> listPtrs;
    }

    _CrtDumpMemoryLeaks();

    return 0;
}
同样,如果在main返回由
std::vector
分配的任何资源后调用
\u CrtDumpMemoryLeaks
,则应该释放。这也是因为
listPtrs
现在已超出范围,并且调用了
std::vector
的析构函数

#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <vector>

// Call _CrtDumpMemoryLeaks after main has returned and before program terminates.
struct AtExit
{
    ~AtExit() { _CrtDumpMemoryLeaks(); }
} doAtExit;

int main()
{
    std::vector<struct Foo*> listPtrs;

    return 0;
}

std::vector
不会导致内存泄漏,粗心的程序员会这样做。您还应该包括一个实际展示您正在经历的行为的示例,包括对CRT调试API的调用。很可能是您根据报告时间错误地解释了泄漏。您显示的两个示例中都没有内存泄漏。
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#include <vector>
#include <memory>

// Call _CrtDumpMemoryLeaks after main has returned and before program terminates.
struct AtExit
{
    ~AtExit() { _CrtDumpMemoryLeaks(); }
} doAtExit;

int main()
{
    std::vector<std::unique_ptr<struct Foo*>> listPtrs;

    return 0;
}