template<typename T>
class shared_ptr
{
T *_ptr;
std::size_t *count;
std::function<void(T*)> del{ DebugDelete() }; //DebugDelete只是delete 指针
//....
public:
shared_ptr(T *t = new T, std::function<void(T*)> f=DebugDelete)
:_ptr(t), count(new std::size_t(1),del(f) {}
//....
~shared_ptr()
{
if (--*count == 0)
{
del(_ptr); //删除器
delete count;
}
}
};
但是这样就和库的shared_ptr的使用不一样了,例如原版的shared_ptr定义一个指向vector<int>的指针:shared_ptr<vector<int>> vint_ptr;
它不用指定删除器,这是怎么实现的?在删除器下工夫?
怪我咯2017-04-17 13:34:06
The second parameter in the shared_ptr constructor in the standard library allows you to customize a deleter to release resources during destruction. If not specified, it will simply delete the raw pointer. Vector, a type that is not responsible for holding resources, does not need to customize a deleter.