//DeleteObject.h
class Item;
class DeleteObject
...{
public:
DeleteObject(void);
public:
~DeleteObject(void);
void DeleteItem(Item* p);
};
//DeleteObject.cpp
#include "StdAfx.h"
#include "DeleteObject.h"
#include <boost/checked_delete.hpp>
DeleteObject::DeleteObject(void)
...{
}
DeleteObject::~DeleteObject(void)
...{
}
void DeleteObject::DeleteItem( Item* p )
...{
delete p;
}//item.h
#include <iostream>
class Item
...{
public:
~Item()
...{
std::cout<<"Item destruction ";
}
};//main.cpp
#include "DeleteObject.h"
#include "Item.h"
DeleteObject del;
del.DeleteItem(new Item);
/////////////////////////////////
结果Item的析构函数没有被调用~
这是因为DeleteObject并不知道Item的详细定义,这是C++中一个很危险的错误!(还好编译器一般都给warning)
怎么解决这个问题呢?
利用Boost库中的checked_delete
定义如下:
template<class T> inline void checked_delete(T * x)
...{
// intentionally complex - simplification causes regressions
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete x;
}
template<class T> inline void checked_array_delete(T * x)
...{
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete [] x;
}可以看到利用C的一个语法——数组长度必须大于零,来解决这个问题,typedef是发生在编译期,而sizeof同样是在编译期,所以这两行代码不会对程序的效率空间等等产生任何影响,只会在上面所举的例子发生的时候报编译错误。
现在将代码改为:
void DeleteObject::DeleteItem( Item* p )
...{
boost::checked_delete(p);
}
本文探讨了C++中安全删除对象的问题,特别是在不完全类型信息的情况下。通过实例展示了使用Boost库中的checked_delete函数如何避免因类型信息缺失导致的错误,并确保正确的资源释放。
4750

被折叠的 条评论
为什么被折叠?



