In C++, there are four memory management operators that are used to dynamically allocate and deallocate memory at runtime:
new
: Thenew
operator is used to dynamically allocate memory for an object or an array of objects. It returns a pointer to the beginning of the allocated memory. Thenew
operator can also be used to initialize the allocated memory with a specific value.delete
: Thedelete
operator is used to deallocate memory that was previously allocated using thenew
operator. It takes a pointer to the allocated memory as an argument and returns the memory to the system.new[]
: Thenew[]
operator is used to dynamically allocate an array of objects. It returns a pointer to the beginning of the allocated memory.delete[]
: Thedelete[]
operator is used to deallocate an array of objects that was previously allocated using thenew[]
operator. It takes a pointer to the allocated memory as an argument and returns the memory to the system.
Here is an example of how to use the new
and delete
operators to dynamically allocate and deallocate memory for a single object:
#include <iostream>
int main()
{
int *p = new int; // Allocate memory for an int object
*p = 10; // Initialize the allocated memory with the value 10
std::cout << *p << std::endl; // Prints 10
delete p; // Deallocate the memory
return 0;
}
And here is an example of how to use the new[]
and delete[]
operators to dynamically allocate and deallocate memory for an array of objects:
#include <iostream>
int main()
{
int *p = new int[10]; // Allocate memory for an array of 10 int objects
for (int i = 0; i < 10; i++)
{
p[i] = i; // Initialize the allocated memory with the values 0 to 9
}
for (int i = 0; i < 10; i++)
{
std::cout << p[i] << " "; // Prints 0 1 2 3 4 5 6 7 8 9
}
std::cout << std::endl;
delete[] p; // Deallocate the memory
return 0;
}
Overall, the memory management operators in C++ are important tools that allow you to dynamically allocate and deallocate memory at runtime, and they are essential for many applications that require flexible memory usage.