Creating an object and giving ownership to a container using a unique_ptr is no problem. How would one remove an element by raw pointer?
std::set<std::unique_ptr<MyClass>> mySet;
MyClass *myClass = new MyClass();
mySet.insert(std::unique_ptr<MyClass>(myClass));
// remove myClass from mySet?
You will need to find the iterator corresponding to the myClass
element and then pass that iterator to mySet.erase()
. The iterator may be found using the std::find_if
algorithm with a custom Predicate
functor that understands how to dereference unique_ptr
and compare it to the raw pointer myClass
.
You can not use the overloaded size_t set::erase ( const key_type& x );
since the raw pointer (even if wrapped in a temporary unique_ptr
) will not be found in mySet
.