Why can’t it just be regular function calls? New is essentially:
malloc(sizeof(Foo));
Foo::Foo();
While delete is
Foo:~Foo();
free(...);
So why does new/delete end up having it’s own syntax rather than being regular functions?
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.
Here’s a stab at it:
The
newoperator calls theoperator new()function. Similarly, thedeleteoperator calls theoperator delete()function (and similarly for the array versions).So why is this? Because the user is allowed to override
operator new()but not thenewoperator (which is a keyword). You overrideoperator new()(and delete) to define your own allocator, however, you are not responsible (or allowed to for that matter) for calling appropriate constructors and destructors. These function are called automatically by the compiler when it sees thenewkeyword.Without this dichotomy, a user could override the
operator new()function, but the compiler would still have to treat this as a special function and call the appropriate constructor(s) for the object(s) being created.