Wrapping a releaseable object into a smart pointer

前端 未结 3 1474
执笔经年
执笔经年 2021-01-25 19:41

As far as I understand the smart pointers, they are there to avoid memory leaks among other things. However there are often objects which also need to be released, but not by

3条回答
  •  粉色の甜心
    2021-01-25 20:24

    If you are using unique_ptr or shared_ptr, you can provide your custom deleter. The deleter for a unique_ptr is passed as a template parameter, and

    Deleter must be FunctionObject or lvalue reference to a FunctionObject or lvalue reference to function, callable with an argument of type unique_ptr::pointer

    For the shated_ptr, the deleter should be provided as the constructor parameter.

    class Foo
    {
    
    };
    
    class Deleter
    {
    public:
        void operator()(Foo *)
        {
            std::cout << "deleter";
        }
    };
    
    int main() {
        std::unique_ptr ptr(new Foo());
        std::shared_ptr ptr1(new Foo(),
                                 [](Foo*){std::cout << "deleter for shared_ptr";}
                                 );
    }
    

    You have to be careful not to cause memory leaks, though.

提交回复
热议问题