Search code examples
c++c++11shared-ptr

Using the pointer returned from a std::shared_ptr<T>.get() function to delete an object?


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 will be deleted 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?

Solution

  • The shared_ptr doesn't know you delete the pointer you got from .get(). So when the shared_ptr itself is destroyed it will also try to delete the object - leading to a double delete which is undefined behaviour. Additionally, dereferencing a pointer to a deleted object is also UB.

    delete marks the memory occupied by the object as "free to be re-used" and calls the objects destructor. After delete you are not allowed (under pain of invoking UB) to ever access the object again.

    Your program is simply invalid and anything the compiler may generate is allowed.