c++ - shared_ptr智能指针的释放和删除器的问题。
伊谢尔伦
伊谢尔伦 2017-04-17 13:32:06
0
1
387
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;
它不用指定删除器,这是怎么实现的?在删除器下工夫?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
刘奇

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template