C++ defines two operators, new
and delete
, that allocate memory from the free store and release memory back into the free store.
The new
operator is used with the type to allocate memory, and it will return a typed pointer to that memory:
int *p = new int; // allocate memory for one int
The new
operator will call the default constructor for custom types for every object it creates (as explained in Chapter 4, Classes). Built-in types do not have constructors, so instead a type initialization will occur and this will usually initialize the object to zero (in this example, a zero integer).
In general, you should not use memory allocated for built-in types without explicitly initializing it. In fact, in Visual C++ the debug version of the new
operator will initialize memory to a value of 0xcd
for every byte, as a visual reminder in the debugger that you have not initialized the memory. For custom types, it is left to the author of the type...