Wrapping a releaseable object into a smart pointer

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

    You can construct both shared_ptr (signature #3 here) and unique_ptr (signature #2 here) with custom deleters.

    using T = ...;
    auto deleter = [](T* x) { delete x; };
    
    // different deleter - different unique_ptr type
    // deleter is stored inline
    auto x = std::unique_ptr(new T(...), deleter);
    
    // same shared_ptr type regardless of the deleter type,
    // deleter is stored in the "shared state"
    auto y = std::shared_ptr(new T(...), deleter);
    

    Note, make_shared() cannot be used to construct a shared_ptr with custom deleter.

提交回复
热议问题