首页 > C/C++ > 查内存泄露之打印程序对象个数

查内存泄露之打印程序对象个数

2010年10月1日 发表评论 阅读评论

当程序中的对象使用了智能指针后,很有可能因为互相引用导致的内存泄露,这个时候,可以在程序运行过程中打印出每个对象的个数。原理就是自己写一个map,索引是对象的名字,值为个数,每次构造的时候++,每次析构的时候–。大概代码如下:

count_object_allocate.h

#ifndef _COUNT_OBJECT_ALLOCATE_H_
#define _COUNT_OBJECT_ALLOCATE_H_
 
#include <map>
#include <string>
#include <typeinfo>
 
class object_counter
{
public:
	object_counter();
	~object_counter();
	static object_counter * get_counter();
	bool add_object_count( const char * object_name );
	bool delete_object_count( const char * object_name );
 
	void dump_all_objects();
 
private:
	std::map<std::string , int> allocated_objects_;
};
 
template<typename T>
class count_object_allocate
{
public:
	count_object_allocate()
	{
		object_counter::get_counter()->add_object_count( typeid(T).name() );
	}
 
	~count_object_allocate()
	{
		object_counter::get_counter()->delete_object_count( typeid(T).name() );
	}
 
    count_object_allocate(const count_object_allocate<T> & coa)
    {
        object_counter::get_counter()->add_object_count( typeid(T).name() );
    }
};
#endif

count_object_allocate.cpp

#include "Common.h"
#include "count_object_allocate.h"
 
#ifdef DUMP_OBJECT
object_counter g_count;
#endif
 
object_counter::object_counter()
{
}
 
object_counter::~object_counter()
{
}
 
#ifdef DUMP_OBJECT
object_counter * object_counter::get_counter()
{
	return &g_count;
}
#endif
 
bool object_counter::add_object_count( const char * object_name )
{
	std::map<std::string , int>::iterator iter = this->allocated_objects_.find( object_name );
	if ( iter == this->allocated_objects_.end() ) 
        {
		// new
		this->allocated_objects_.insert( std::make_pair( object_name , 0 ) );
		iter = this->allocated_objects_.find( object_name );
	}
 
	iter->second++;
 
    return true;
}
 
bool object_counter::delete_object_count( const char * object_name )
{
	std::map<std::string , int>::iterator iter = this->allocated_objects_.find( object_name );
	if ( iter == this->allocated_objects_.end() ) 
        {
		// new
		return false;
	}
 
	iter->second--;
 
    return true;
}
 
void object_counter::dump_all_objects()
{
	printf("begin dump objects:\r\n");
	for ( std::map<std::string , int>::iterator i = this->allocated_objects_.begin() ;
             i != this->allocated_objects_.end() ; ++i ) 
        {
		printf("%s\t\t: %d\r\n" , i->first.c_str() , i->second);
	}
	printf("end dump objects:\r\n");
}

在使用的过程中,每个类只需要继承count_object_allocate即可,感谢nightsuns提供的好办法!

分类: C/C++ 标签: ,
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.