C++ Map中存储动态指针时正确释放内存

#ifdef _DEBUG
#define DEBUG_CLIENTBLOCK   new( _CLIENT_BLOCK, __FILE__, __LINE__)
#else
#define DEBUG_CLIENTBLOCK
#endif
#define _CRTDBG_MAP_ALLOC
#include 
#ifdef _DEBUG
#define new DEBUG_CLIENTBLOCK
#endif

#include 
#include 
#include 

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 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::iterator iter = MyTestMap.begin();

	while (iter != MyTestMap.end())
	{
		delete iter->second;
		iter->second = NULL;
		iter = MyTestMap.erase(iter);
	}

	MyTestMap.clear();

	getchar();
	_CrtDumpMemoryLeaks();

	return 0;
}



如果您觉得这篇博文有用,请访问我的个人站:http://www.stubbornhuang.com/,更多博文干货等着您。

你可能感兴趣的:(C++)