If I were to allocate new memory for a local character array in a function using “new”, would it be necessary to use delete prior to the function return?
Wouldn’t it automatically be deleted after the function return anyway?
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.
Yes, it is necessary: if you allocate something on the dynamic store with
newornew[], the compiler has no idea that you have no plans to pass the allocated object along after the function returns, so it is your responsibility to calldelete(ordelete[]) to free the object that you have allocated.You can use
unique_ptr<T>to avoid calling thedeleteexplicitly, but the call will be made by the destructor ofunique_ptr<T>on your behalf.