Wrapping a releaseable object into a smart pointer

前端 未结 3 1475
执笔经年
执笔经年 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:11

    Both shared_ptr and unique_ptr provide that facility.


    For shared_ptr, the constructor is a template:

    An optional deleter d can be supplied that is later used to destroy the object when no shared_ptr objects own it. By default, a delete-expression for type Y is used as the deleter.

    In this case, the deleter can be any callable, copy-constructible value, which get type-erased to the callable.

    For unique_ptr, the type of the deleter is a type parameter of the pointer itself:

    template<
        class T,
        class Deleter = std::default_delete
    > class unique_ptr;
    

    There's no erasure in this case, and the deleter provided to the c-tor or the reset actually matches the deleter type.

提交回复
热议问题