FAQ 12.02 Why is new better than good old trustworthy malloc() ?

FAQ 12.02 Why is new better than good old trustworthy malloc()?

graphics/new_icon.gif

It does more.

Object construction: In C++, new and delete create and destroy objects. In contrast, malloc() and free() merely allocate and deallocate memory.

Safety: The new operator returns a pointer of the correct type whereas the function malloc() returns a void*, which isn't type safe. The C language allows a void* to be converted to any other pointer, but this is a dangerous hole in C's type-checking system. C++ doesn't have this weakness: converting a void* to a different pointer type requires an explicit cast in C++.

Flexibility: The new operator can be overloaded by a class. For example, new Fred() can use a different memory allocation primitive than is used by new Wilma(). In contrast, malloc() cannot be overloaded on a class-by-class basis.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net