Using a std::unordered_set of std::unique_ptr

后端 未结 4 2076
南旧
南旧 2021-01-07 16:40

Assume I have a set of unique_ptr:

std::unordered_set > my_set;

I\'m not sure what\'s the safe way to

4条回答
  •  迷失自我
    2021-01-07 17:15

    You can also use a deleter that optionally doesn't do anything.

    template
    struct maybe_deleter{
      bool _delete;
      explicit maybe_deleter(bool doit = true) : _delete(doit){}
    
      void operator()(T* p) const{
        if(_delete) delete p;
      }
    };
    
    template
    using set_unique_ptr = std::unique_ptr>;
    
    template
    set_unique_ptr make_find_ptr(T* raw){
        return set_unique_ptr(raw, maybe_deleter(false));
    }
    
    // ...
    
    int* raw = new int(42);
    std::unordered_set> myset;
    myset.insert(set_unique_ptr(raw));
    
    auto it = myset.find(make_find_ptr(raw));
    

    Live example.

提交回复
热议问题