How does the custom deleter of std::unique_ptr work?

后端 未结 4 502
青春惊慌失措
青春惊慌失措 2020-11-27 11:47

According to N3290, std::unique_ptr accepts a deleter argument in its constructor.

However, I can\'t get that to work with Visual C++ 10.0 or MinGW g++

4条回答
  •  感动是毒
    2020-11-27 12:13

    To complement all previous answers, there is a way to have a custom deleter without having to "pollute" the unique_ptr signature by having either a function pointer or something equivalent in it like this:

    std::unique_ptr< MyType, myTypeDeleter > // not pretty
    

    This is achievable by providing a specialization to the std::default_delete template class, like this:

    namespace std
    {
    template<>
    class default_delete< MyType >
    {
    public:
      void operator()(MyType *ptr)
      {
        delete ptr;
      }
    };
    }
    

    And now all std::unique_ptr< MyType > that "sees" this specialization will be deleted with it. Just be aware that it might not be what you want for all std::unique_ptr< MyType >, so chose carefully your solution.

提交回复
热议问题