Operator New

Operator New - Operator New/Delete In the first newsletter...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Operator New/Delete In the first newsletter we talked about using C++ as a better C. This term doesn't have a precise meaning, but one way of looking at it is to focus on the features C++ adds to C, exclusive of the most obvious one, namely the class concept used in object- oriented programming. One of these features is operator new and operator delete. These are intended to replace malloc() and free() in the C standard library. To give an example of how these are similar and how they differ, suppose that we want to allocate a 100-long vector of integers for some purpose. In C, we would say: int* ip; ip = (int*)malloc(sizeof(int) * 100); ... free((void*)ip); With new/delete in C++, we would have: int* ip; ip = new int[100]; ... delete ip; The most obvious difference is that the C++ approach takes care of the low-level details necessary to determine how many bytes to allocate. With the C++ new operator, you simply describe the type of the desired storage, in this example "int[100]". The C and C++ approaches have several similarities: - neither malloc() nor new initialize the space to zeros - both malloc() and new return a pointer that is suitably aligned for a given machine architecture - both free() and delete do nothing with a NULL pointer malloc() returns NULL if the space cannot be obtained. Many versions of new in existing C++ compilers do likewise. However, the draft ANSI C++ standard says that
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 4

Operator New - Operator New/Delete In the first newsletter...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online