In order for an application to have no memory leaks, does the number of new in a C++ project match the number of delete?
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 mean do you need the same number of instances of
deletein your source code as you have instances ofnew, then no. You can have objectsnewed in multiple places, but all these objectsdeleted by the same line of code. In fact this is a common idiom.Smart pointers, of varying types, generally take many different objects
newed in many places in user code anddeletethem from a single place in library code.Edit
Technically, every successfully memory allocation call needs to be matched with a dellocation call that takes the returned pointer from the original allocation call.
Most
newexpressions result in a call to anoperator newthat allocates the memory and the constructs an object in the newly allocated memory. Using adeleteexpression destroys the object and causes a call to anoperator deletethat should free the allocated memory.There are new expressions that construct objects in pre-allocated memory (placement
new). These should not be matched by a delete expression, but the pre-allocated memory may need to be deallocated in a way that corresponds to the original allocation.