I know how they are different syntactically, and that C++ uses new, and C uses malloc. But how do they work, in a high-level explanation?
See What is the difference between new/delete and malloc/free?
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.
I’m just going to direct you to this answer: What is the difference between new/delete and malloc/free? . Martin provided an excellent overview. Quick overview on how they work (without diving into how you could overload them as member functions):
new-expression and allocation
Sample:
new_handler, and hope it makes place. If there still is not enough place, new has to throwstd::bad_allocor derived from it. An allocator that hasthrow()(no-throw guarantee), it shall return a null-pointer in that case.There are a few special allocation functions given special names:
no-thrownew. That takes anothrow_tas second argument. A new-expression of the form like the following will call an allocation function taking only std::size_t and nothrow_t:Example:
placement new. That takes a void* pointer as first argument, and instead of returning a newly allocated memory address, it returns that argument. It is used to create an object at a given address. Standard containers use that to preallocate space, but only create objects when needed, later.Code:
If the allocation function returns storage, and the the constructor of the object created by the runtime throws, then the operator delete is called automatically. In case a form of new was used that takes additional parameters, like
Then the operator delete that takes those parameters is called. That operator delete version is only called if the deletion is done because the constructor of the object did throw. If you call delete yourself, then the compiler will use the normal operator delete function taking only a
void*pointer:new-expression and arrays
If you do
The compiler is using the
operator new[]functions instead of plainoperator new. The operator can be passed a first argument not exactlysizeof(TypeId)*N: The compiler could add some space to store the number of objects created (necassary to be able to call destructors). The Standard puts it this way:new T[5]results in a call of operatornew[](sizeof(T)*5+x), andnew(2,f) T[5]results in a call of operatornew[](sizeof(T)*5+y,2,f).