Sure, in C++ the new operator is used for dynamically allocating memory on the heap. When you use , memory is allocated, and a pointer to this memory is returned. Here's a basic overview of how to use the operator, including examples for scalar types, arrays, and objects of classes.
new
new
Allocating Single Element
For allocating a single element (e.g., an int or a float), you can use the new operator as follows:
int* p = new int; // Allocates memory for a single int and returns a pointer to it
*p = 5; // Assigns the value 5 to the allocated int
// Don't forget to free the allocated memory when it is no longer needed.
delete p;
Allocating Arrays
For allocating an array of elements, you can use the new operator with square brackets:
int* arr = new int[10]; // Allocates memory for an array of 10 ints
// Use the allocated array
for (int i = 0; i < 10; ++i) {
arr[i] = i * 2;
}
// Free the allocated array
delete[] arr;
Allocating Objects
For allocating objects of a class, you can use the new operator. The constructor of the class will be called automatically.
class MyClass {
public:
MyClass() {
// Constructor code
}
~MyClass() {
// Destructor code
}
};
MyClass* obj = new MyClass; // Allocates memory for a MyClass object and calls its constructor
// Use the allocated object
// e.g., obj->someMethod();
// Free the allocated object
delete obj;
Allocating Array of Objects
For an array of objects, similar to primitive types, you use square brackets, and the constructor for each object in the array will be called:
MyClass* objArray = new MyClass[5]; // Allocates an array of 5 MyClass objects
// Use the allocated objects
// e.g., objArray[0].someMethod();
// Free the allocated array of objects
delete[] objArray;
Important Points to Note:
Memory Leak Prevention: Always ensure that each new has a corresponding delete (or delete[] for arrays) to avoid memory leaks.
Null Check: It's a good practice to check if the allocation succeeded by checking if the return pointer is not nullptr.
Custom Deleters: If your class allocates additional resources, make sure its destructor properly releases these resources to prevent resource leaks.
By using the new and delete operators correctly, you can effectively manage dynamic memory in your C++ programs.