A blog describing computer internals and electronics, from a student's viewpoint

"Paperbacks"

Tuesday, April 14, 2009

C++: The new and delete operators

If you have been accustomed to C, you may encounter the way heap memory is allocated:

char* c = (char*)malloc(sizeof(char) * x);

In C++, due to the existence of classes and constructors/destructors, malloc and free alone won't suffice; it won't be able to call the constructor and destructor, respectively. So, the keyword new was made to allocate the memory and call the constructor. The previous item will now look like this:

char* c = new char[x];

Notice that sizeof(char) is gone. Why? Because new will, in order to return the correct pointer type, need to know the type of data you are allocating, and the operator determines the size of an element from the type. The general syntax of the new keyword is:

(data type)* x = new (data type)[y];

where x is the pointer to store the address of the allocated memory, and y is the number of elements. When y = 1, the [y] part can be omitted:

(data type)* x = new (data type);

Notice new's two forms: the former, with the square brackets, is called vector new; the one without the brackets is called scalar new.

On the other hand, delete does the reverse: it calls the destructor before putting the memory back to the heap. The delete operator has two forms:

delete - for single-element allocations (scalar)

delete[] - for multi-element (array) allocations (vector)

To avoid being too technical, as I've done in some posts, the versions with the square brackets are for array (vector) allocations/deallocations, while the versions without the brackets are for one-element (scalar) allocations/deallocations.

No comments:

Post a Comment