When a pointer goes out of scope, its memory is freed, so why are destructors created in c++?
When a pointer goes out of scope, its memory is freed, so why are
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you’re asking why C++ classes have destructors, some classes have requirements other than just freeing memory. You may have an object that’s allocated a socket connection that needs to be shut down cleanly, for example.
Also, ‘unscoping’ a pointer does not free the memory that it points to since other pointers may be referencing it.
If you have a pointer on the stack, exiting the function will free the memory used by the pointer but not that memory pointed to by the pointer. There’s a subtle but very important distinction.