如何避免野指针
2013-01-09 22:38
232 查看
Form:知然工作室(http://www.cnblogs.com/zhiranok/archive/2012/12/22/cpp_memleak.html)
我们其实需要的是这样的指针:
一种指针,引用了另一个对象的地址(不然就不是指针了),当目标对象销毁时,该指针自然指向null,而不需要目标对象主动通知重置。
幸运的是,这种指针已经有了,就是weak_ptr; 在boost库中,sharedptr,scopedptr,weakptr统称为smartptr。可以尽量使用智能指针,避免野指针。本人建议尽量使用shared_ptr结合weak_ptr使用。Scoped_ptr本人使用的较少,只是在创建线程对象的时候使用,正好符合不能复制的语义。使用shared_ptr和weak_ptr的示例代码:
有人问monster_t为什么不直接使用shared_ptr,如果使用shared_ptr就不符合现实的模型了,monster_t显然不应该控制player_t的生命周期,如果使用了shared_ptr,那么可能导致player_t被延迟析构,甚至会导致内存暴涨。这也是shared_ptr的使用误区,所以本人建议尽量shared_ptr和weak_ptr结合用,否则野指针问题解决了,内存泄漏问题又来了。
首先说明本方法区别于valgrind等工具,该工具是调试期进行的检测,本文探究的是运行期的检测,确切说是运行期定时输出所有对象的数量到日志中。
首先定义分配、释放对象的接口:
为了节省篇幅,这里只列举了三种构造的代码,当分配对象时,对应的类型数量增加1,obj_counter 使用原子操作为每一种类型记录其数量。
class obj_counter_i
{
public:
obj_counter_i():m_ref_count(0){}
virtual ~ obj_counter_i(){}
void inc(int n) { (void)__sync_add_and_fetch(&m_ref_count, n); }
void dec(int n) { __sync_sub_and_fetch(&m_ref_count, n); }
long val() const{ return m_ref_count; }
virtual string get_name() { return ""; }
protected:
volatile long m_ref_count;
};
template<typename T>
class obj_counter_t: public obj_counter_i
{
obj_counter_t()
{
singleton_t<obj_counter_t<T> >::instance().reg(this);
}
virtual string get_name() { return TYPE_NAME(T); }
};
相应的当对象被释放的时候,对应的对象数量减一,示例代码如下:
template<typename T>
void del_obj(T* p)
{
if (p)
{
delete p;
singleton_t<obj_counter_t<T> >::instance().dec(1);
}
}
这样就做到了所有的对象的数量都被记录了,可以定时的将对象数量输出到文件:
我们其实需要的是这样的指针:
一种指针,引用了另一个对象的地址(不然就不是指针了),当目标对象销毁时,该指针自然指向null,而不需要目标对象主动通知重置。
幸运的是,这种指针已经有了,就是weak_ptr; 在boost库中,sharedptr,scopedptr,weakptr统称为smartptr。可以尽量使用智能指针,避免野指针。本人建议尽量使用shared_ptr结合weak_ptr使用。Scoped_ptr本人使用的较少,只是在创建线程对象的时候使用,正好符合不能复制的语义。使用shared_ptr和weak_ptr的示例代码:
class monster_t { protected: weak_ptr<player_t> m_attack; shared_ptr<player_t> get_attack() { return shared_ptr<player_t>(m_attack); } public: void handle_ai() { shared_ptr<player_t> attack = get_attack(); if (attack) { int x = attack->get_x(); } } }
有人问monster_t为什么不直接使用shared_ptr,如果使用shared_ptr就不符合现实的模型了,monster_t显然不应该控制player_t的生命周期,如果使用了shared_ptr,那么可能导致player_t被延迟析构,甚至会导致内存暴涨。这也是shared_ptr的使用误区,所以本人建议尽量shared_ptr和weak_ptr结合用,否则野指针问题解决了,内存泄漏问题又来了。
内存泄漏:
野指针问题可以通过采用良好的编程范式,尽量规避,但总计c++规避内存泄漏的方法却很为难,简单而言尽量保证对象的分配和释放(分别)是单个入口的,这样大部分问题都可以拦截在code review阶段。那么怎么检测内存泄漏呢?首先说明本方法区别于valgrind等工具,该工具是调试期进行的检测,本文探究的是运行期的检测,确切说是运行期定时输出所有对象的数量到日志中。
首先定义分配、释放对象的接口:
template<typename T> T* new_obj() { T* p = new T(); singleton_t<obj_counter_t<T> >::instance().inc(1); return p; } template<typename T, typename ARG1> T* new_obj(ARG1 arg1) { T* p = new T(arg1); singleton_t<obj_counter_t<T> >::instance().inc(1); return p; } template<typename T, typename ARG1, typename ARG2> T* new_obj(ARG1 arg1, ARG2 arg2) { T* p = new T(arg1, arg2); singleton_t<obj_counter_t<T> >::instance().inc(1); return p; } template<typename T> T* new_array(int n) { T* p = new T ; singleton_t<obj_counter_t<T> >::instance().inc(n); return p; }
为了节省篇幅,这里只列举了三种构造的代码,当分配对象时,对应的类型数量增加1,obj_counter 使用原子操作为每一种类型记录其数量。
class obj_counter_i
{
public:
obj_counter_i():m_ref_count(0){}
virtual ~ obj_counter_i(){}
void inc(int n) { (void)__sync_add_and_fetch(&m_ref_count, n); }
void dec(int n) { __sync_sub_and_fetch(&m_ref_count, n); }
long val() const{ return m_ref_count; }
virtual string get_name() { return ""; }
protected:
volatile long m_ref_count;
};
template<typename T>
class obj_counter_t: public obj_counter_i
{
obj_counter_t()
{
singleton_t<obj_counter_t<T> >::instance().reg(this);
}
virtual string get_name() { return TYPE_NAME(T); }
};
相应的当对象被释放的时候,对应的对象数量减一,示例代码如下:
template<typename T>
void del_obj(T* p)
{
if (p)
{
delete p;
singleton_t<obj_counter_t<T> >::instance().dec(1);
}
}
这样就做到了所有的对象的数量都被记录了,可以定时的将对象数量输出到文件:
class obj_counter_summary_t { public: void reg(obj_counter_i* p) { m_all_counter.push_back(p); } map<string, long> get_all_obj_num() { map<string, long> ret; for (list<obj_counter_i*>::iterator it = m_all_counter.begin(); it != m_all_counter.end(); ++it) { ret.insert(make_pair((*it)->get_name(), (*it)->val())); } return ret; } void dump(const string& path_) { ofstream tmp_fstream; tmp_fstream.open(path_.c_str()); map<string, long> ret = get_all_obj_num(); map<string, long>::iterator it = ret.begin(); time_t timep = time(NULL); struct tm *tmp = localtime(&timep); char tmp_buff[256]; sprintf(tmp_buff, "%04d%02d%02d-%02d:%02d:%02d", tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec); char buff[1024] = {0}; snprintf(buff, sizeof(buff), "obj,num,%s\n", tmp_buff); tmp_fstream << buff; for (; it != ret.end(); ++it) { snprintf(buff, sizeof(buff), "%s,%ld\n", it->first.c_str(), it->second); tmp_fstream << buff; } tmp_fstream.flush(); } protected: list<obj_counter_i*> m_all_counter; };
相关文章推荐
- 什么是野指针 如何避免野指针
- C中的野指针—如何避免
- 什么是野指针以及如何避免野指针?
- C++中指针悬挂问题的产生以及如何避免
- 如何避免java中的空指针
- 如何避免野指针(详解)
- 如何避免野指针?
- 如何避免野指针?
- 野指针如何避免
- 什么是野指针?野指针的危害?如何避免野指针?
- 如何避免野指针
- 1.如何避免野指针2.获取字符串的两种方法。以及malloc,calloc,ralloc的使用注意点3.二维三维数组4.数组和函数的区别
- 如何避免野指针?
- 如何做到避免野指针
- 什么是野指针如何避免野指针
- 什么是野指针?如何避免野指针?
- 如何避免“野指针”
- C中的野指针—如何避免
- 什么是野指针,如何避免?
- C中的野指针—如何避免