- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 371字
- 2021-06-10 18:27:58
Allocating individual objects
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 to initialize allocated memory.
It is important that when you have finished with memory that you return it back to the free store so that the allocator can reuse it. You do this by calling the delete operator:
delete p;
When you delete a pointer, the destructor for the object is called. For built-in types, this does nothing. It is good practice to initialize a pointer to nullptr, after you have deleted it, and if you use the convention of checking the value of a pointer before using it, this will protect you from using a deleted pointer. The C++ standard says that the delete operator will have no effect if you delete a pointer that has a value of nullptr.
C++ allows you to initialize a value at the time you call the new operator, in two ways:
int *p1 = new int (42);
int *p2 = new int {42};
For a custom type, the new operator will call a constructor on the type; for a built in type, the end result is the same, and is carried out by initializing the item to the value provided. You can also use initialized list syntax, as shown in the second line in the preceding code. It is important to note that the initialization is the memory pointed to, not the pointer variable.