使用std :: unique_ptr的std :: unordered_set [英] Using a std::unordered_set of std::unique_ptr
问题描述
假设我有一组unique_ptr:
Assume I have a set of unique_ptr:
std::unordered_set <std::unique_ptr <MyClass>> my_set;
我不知道什么是安全的方式来检查一个给定的指针是否存在于集合。正常的做法是调用 my_set.find()
,但是作为参数传递什么?
I'm not sure what's the safe way to check if a given pointer exists in the set. The normal way to do it may be to call my_set.find ()
, but what do I pass as a parameter?
我从外面所有我都是一个原始的指针。所以我必须从指针创建另一个unique_ptr,传递给 find()
,然后 release()
,否则对象会被破坏(两次)。当然,这个过程可以在一个函数中完成,因此调用者可以传递raw指针,并进行转换。
All I have from the outside is a raw pointer. So I have to create another unique_ptr from the pointer, pass it to find()
and then release()
that pointer, otherwise the object would get destructed (twice). Of course, this process can be done in a function, so the caller can pass the raw pointer and I do the conversions.
这个方法是否安全?有没有更好的方法来处理一组unique_ptr?
Is this method safe? Is there a better way to work with a set of unique_ptr?
推荐答案
也可以使用一个可选的
template<class T>
struct maybe_deleter{
bool _delete;
explicit maybe_deleter(bool doit = true) : _delete(doit){}
void operator()(T* p) const{
if(_delete) delete p;
}
};
template<class T>
using set_unique_ptr = std::unique_ptr<T, maybe_deleter<T>>;
template<class T>
set_unique_ptr<T> make_find_ptr(T* raw){
return set_unique_ptr<T>(raw, maybe_deleter<T>(false));
}
// ...
int* raw = new int(42);
std::unordered_set<set_unique_ptr<int>> myset;
myset.insert(set_unique_ptr<int>(raw));
auto it = myset.find(make_find_ptr(raw));
这篇关于使用std :: unique_ptr的std :: unordered_set的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!