读书人

最近正在对数据结构发起猛烈的进攻于

发布时间: 2012-02-09 18:22:27 作者: rapoo

最近正在对数据结构发起猛烈的进攻,于是想问问各位老鸟,是否有什么一种很简易的方法可以对很方便地对程序内存泄露情况进行检查?谢谢!
Thanx!

[解决办法]
用智能指针可以避免内存泄露,但检查比较麻烦了,不懂.
[解决办法]
意识决定态度,态度决定结果。
写代码的时候时刻想着是不是会有内存泄露,然后再用工具验证之。
[解决办法]
一种办法是将内存的接口全部接管过来,申请就记录下来,释放的话就将记录删除,然后在程序退出的时候查看记录就好了

如果是VC的话,可以用CRTDBG_MAP_ALLOC,你google一下这个,就能找到使用方法
[解决办法]
就C++来说,没什么好方法
[解决办法]
还是自己注意吧, 对自己的行为要负责...既然申请了就一定记得释放;
智能指针也有局限;

下面是vc6中智能指针auto_ptr的说明:

auto_ptr
template<class T>
class auto_ptr {
public:
typedef T element_type;
explicit auto_ptr(T *p = 0) throw();
auto_ptr(const auto_ptr<T>& rhs) throw();
auto_ptr<T>& operator=(auto_ptr<T>& rhs) throw();
~auto_ptr();
T& operator*() const throw();
T *operator->() const throw();
T *get() const throw();
T *release() const throw();
};

The class describes an object that stores a pointer to an allocated object of type T. The stored pointer must either be null or designate an object allocated by a new expression. The object also stores an ownership indicator. An object constructed with a non-null pointer owns the pointer. It transfers ownership if its stored value is assigned to another object. The destructor for auto_ptr<T> deletes the allocated object if it owns it. Hence, an object of class auto_ptr<T> ensures that an allocated object is automatically deleted when control leaves a block, even via a thrown exception.

//好了,估计说了这么多 ,应该知道 auto_ptr的功能和不足了。

//再看看以下我 转过来的文章

STL中的auto_ptr指针是为了解决内存泄漏问题而设计的。它严格限制了指针拥有对指向对象的所有权。auto_ptr指针和普通指针的差别在于对指向对象所有权的处理不同。auto_ptr指针是“传递”所有权,而普通指针是“共享”所有权。看下面例子:

std::auto_ptr<int> p1(new int(24));
std::auto_ptr<int> p2;
int *q1 = new int(12);
int *q2;
p2 = p1;
q2 = q1;
经过两次赋值后,对于auto_ptr,p1为NULL,*p2为24;对于普通指针,*p1, *p2均为12。第一次赋值,p1把指向对象的所有权传递给了p2, p1不再拥有指向对象的所有权。而第二次赋值,q2和q1共享了对同一对象的所有权。因此,对于auto_ptr,一个对象只可能被一个智能指针指向,这样可有效避免内存泄漏问题。但是同时会引起新问题。看下面例子:
template<class T>
void BadPrint(std::auto_ptr<T> p)
{
if (p.get() == NULL)
{
std::cout<<NULL;
}
else
{
std::cout<<*p;
}
}
然后我如下使用BadPrint函数:
std::auto_ptr<int> q(new int(18));
BadPrint(q);
*q = 12;
该程序并未像我们所期望的一样:*q的值为12,而是会出现runtime error,why?因为我们把q作为函数参数传给了BadPrint,因此传递完成后q不再拥有对指向对象的所有权,而函数内部的局部变量p会接管q所指向对象的所有权,当函数执行完毕退出时,p的生命期截止同时delete所指向对象。因此q实际变为NULL,所以出错。如何避免出错?使用auto_ptr的引用?即 void BadPrint(std::auto_ptr<T> &p)。这是相当糟糕的一种做法。对智能指针使用引用混淆了所有权的问题。它导致所有权有可能被传递了,也可能没有被传递。无论如何应当避免对auto_ptr使用引用。
可见智能指针并非对任何情况都智能。使用auto_ptr要知道:
1. 智能指针不能共享指向对象的所有权
2. 智能指针不能指向数组。因为其实现中调用的是delete而非delete[]
3. 智能指针不是万能的
4. 智能指针不能作为容器类的元素。例如:
template<class T>
void container::insert(const T &value)
{
..........
X = value;
..........
}
事实上在stl中,所有的container要内部拷贝所传参数的值时都是传的const类型的值。因此无法用auto_ptr传进去。
、、、、、、、、、、、、、、、、、、、、、
一句话: //一句话,假定有一个动态分配的int空间,则在一个时刻只能有一个auto_ptr指针指向他!
这就是所有权的独占性

[解决办法]
不知道。。
智能指针。?改天再学习下吧

刚笔试完 累死了
[解决办法]
智能指针可以用 boost的 shared_ptr.

读书人网 >C++

热点推荐