Difference between new and delete operator in c++
In C++, new
and delete
are operators used to dynamically allocate and deallocate memory, respectively.
new
operator:
The new
operator is used to dynamically allocate memory for an object or an array. When you use new
, the following happens:
- The memory is allocated from the free store (also known as the heap).
- The memory is initialized with the default constructor of the object (if it has one).
- A pointer to the allocated memory is returned.
Example:
int* p = new int;
This code allocates memory for an int
object and returns a pointer to it.
delete
operator:
The delete
operator is used to deallocate memory that was previously allocated using new
. When you use delete
, the following happens:
- The memory is deallocated from the free store.
- The object's destructor is called (if it has one).
Example:
delete p;
This code deallocates the memory that was allocated using new
and calls the destructor of the int
object.
Key differences:
- Allocation vs. Deallocation:
new
allocates memory, whiledelete
deallocates memory. - Initialization:
new
initializes the memory with the default constructor of the object, whiledelete
does not perform any initialization. - Destruction:
delete
calls the destructor of the object, whilenew
does not. - Return value:
new
returns a pointer to the allocated memory, whiledelete
does not return any value.
Best practices:
- Always use
new
anddelete
together to ensure that memory is properly allocated and deallocated. - Use smart pointers (e.g.,
unique_ptr
,shared_ptr
) instead of raw pointers andnew
/delete
to manage memory. - Avoid using
new
anddelete
in performance-critical code, as they can introduce overhead and potential bugs.
In summary, new
is used to allocate memory and initialize objects, while delete
is used to deallocate memory and destroy objects.