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.
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?)?shared_ptr
s, created from the make_shared
function are destroyed only by the shared_ptr
s themselves?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.