New delete
You're referring to the "new" and "delete" operators in C++!
In C++, new
is a keyword that is used to dynamically allocate memory for an object or an array. When you use new
, you are telling the compiler to create a new object or array in memory and return a pointer to it.
Here's an example:
int* p = new int;
This code allocates memory for an int
object and assigns the address of that memory to the pointer p
.
On the other hand, delete
is a keyword that is used to deallocate memory that was previously allocated using new
. When you use delete
, you are telling the compiler to release the memory back to the system.
Here's an example:
delete p;
This code deallocates the memory that was previously allocated for the int
object using new
.
It's important to use delete
to deallocate memory that was allocated using new
to prevent memory leaks. Memory leaks occur when memory is allocated but not deallocated, which can cause problems for your program.
Here's an example of a memory leak:
int* p = new int;
//...
In this example, the memory is allocated using new
, but it is not deallocated using delete
. This can cause a memory leak.
To avoid memory leaks, it's a good practice to use smart pointers, such as unique_ptr
or shared_ptr
, which automatically manage the memory for you.
Here's an example using unique_ptr
:
std::unique_ptr<int> p(new int);
In this example, the memory is allocated using new
, but it is automatically deallocated when the unique_ptr
object goes out of scope.