C++ – std::map – 存储动态指针时正确释放内存
原创文章,作者:StubbornHuang,如若转载,请注明出处:《C++ – std::map – 存储动态指针时正确释放内存》https://www.stubbornhuang.com/738/
code
#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif
#include <iostream>
#include <map>
#include <string>
using namespace std;
class Example
{
public:
Example();
Example(int newIndex);
virtual ~Example();
int m_Index;
};
Example::Example()
{
}
Example::Example(int newIndex)
{
m_Index = newIndex;
}
Example::~Example()
{
}
int main()
{
std::map<std::string, Example*> MyTestMap;
for (unsigned int i = 0; i < 10; ++i)
{
std::string tempStr = std::to_string(i);
Example* pExample = new Example(i);
MyTestMap[tempStr] = pExample;
}
std::map<std::string, Example*>::iterator iter = MyTestMap.begin();
while (iter != MyTestMap.end())
{
delete iter->second;
iter->second = NULL;
iter = MyTestMap.erase(iter);
}
MyTestMap.clear();
getchar();
_CrtDumpMemoryLeaks();
return 0;
}
当前分类随机文章推荐
- C++11 - 父类与子类相互包含的时候该如何正确的使用智能指针,防止循环引用
- C++ - 字节数组byte与int的相互转换
- C++11/std::thread - 线程的基本用法
- C++ - queue存储动态指针时正确释放内存
- C++11/std::thread - 可作为线程函数的几种方式总结
- C++ - std::map - 存储动态指针时正确释放内存
- C++11/std::shared_ptr - 循环引用问题
- C++ - int转string方法总结
- C++11/std::thread - 线程管理join/detach
- C++11 - override关键字简要介绍