What is the use or what is the reason for new() and delete() to be implemented as operators in c++ ? What are the advantages of making it an operator instead of a function?
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.
The
newoperator cannot be a function because it accepts a type as an argument. You cannot writenew foo_typeas a function call, becausefoo_typeis not an expression that produces a value, but a type name.The
deleteoperator could be a function that is overloaded for different pointer types, and an extra optionalboolargument fordelete []semantics. Why there is adeleteoperator is probably for symmetry with itsnewcounterpart.That said, template functions can take types as template arguments. But the
newanddeleteoperators historically precede templates.Also, a function can be written which takes, instead of a type, a prototype instance of a type, from which an object is constructed:
newobj(m_class(constructor_arg)). Thisnewobjis overloaded for different types. It allocates space, copy constructs into it, and returns the object.So in the end, the design reflects the tastes and whims of the designer.
The separation itself between operators and functions (and statements, declarations, and so on) is not strictly necessary in language design.