leaving the scope, swp1 will invoke the deleter to delete the raw pointer, and then spw2 invoke the same deleter to delete the same raw pointer. It's undefined behavior, and will output error message saying double free.
But the following code works very well ! why ? I have no idea what magic std::shared_ptr or compiler does ?
{
auto wptr = new Widget();
auto deleter = [](Widget* pw)
{
// do something, such as logging.
std::cout << "deleter called" << std::endl;
delete pw;
};
std::shared_ptr<Widget> spw1(wptr, deleter);
std::shared_ptr<Widget> spw2(wptr, deleter);
}
Aucun commentaire:
Enregistrer un commentaire