jeudi 26 mars 2020

Using the pointer returned from a std::shared_ptr

int main(int argc, char *argv[])
{
    auto sp = std::make_shared<int>();
    auto p = sp.get();
    delete p; //here
    std::cout << *sp << std::endl;

    return 0;
}

I was hoping that the object managed by the shared_ptr sp be delete with by the statement commented "here" but the object remains intact and is printed in the output statement.

  • Is this not working because I didn't create the object managed by the shared_ptr explicitly with the new keyword (because every new statement must have a corresponding delete statement and therefore every delete statement, an earlier corresponding new keyword?)?
  • And does this mean that pointed objects managed by shared_ptrs, created from the make_shared function are destroyed only by the shared_ptrs themselves?

Aucun commentaire:

Enregistrer un commentaire