Suppose there is a unordered set of shared pointers. I would like to erase the elements from the unordered set with the knowledge of the raw pointer of that element. If I create a dummy shared pointer from that raw pointer and erase that dummy shared pointer, I got double free. How could I fix the bug? Thank you.
#include <memory>
#include <unordered_set>
#include <iostream>
struct myclass{
myclass(){ std::cout << "constructor\n";}
~myclass(){std::cout << "destructor\n"; }
};
void erase(std::unordered_set<std::shared_ptr<myclass>>& set, myclass* raw_ptr) {
std::shared_ptr<myclass> dummy{raw_ptr};
set.erase(dummy);
}
int main() {
std::unordered_set<std::shared_ptr<myclass>> set;
std::shared_ptr<myclass> s_ptr{new myclass};
auto raw_ptr = s_ptr.get();
erase(set, raw_ptr);
return 0;
}
I would expect the output to be:
constructor destructor