Difference Between New And Delete Operator In C++ - C++ Programming Tutorial
C++ Course / C++ vs Other Languages / Difference Between New And Delete Operator In C++

Difference Between New And Delete Operator In C++

BLUF: Mastering Difference Between New And Delete Operator In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Difference Between New And Delete Operator In C++

C++ is renowned for its efficiency. Learn how Difference Between New And Delete Operator In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, the new and delete operators play a vital role in managing dynamic memory allocation and deallocation. These operators allow us to allocate and release memory dynamically, enabling the creation of objects with sizes and lifetimes determined during runtime.

In this post, we will explore the variance between the new and delete operators in C++. Prior to delving into their distinctions, it is essential to understand the functionality of the new and delete operators in C++.

What is the new Operator in C++?

In C++, the new operator functions as a memory allocation operator that is employed to reserve memory during program execution. This operator assigns memory space from the heap and provides the starting address of the allocated memory, which can be saved in a pointer variable. It enables the allocation of memory in situations where the quantity or size of necessary variables is not determined at compile time.

Syntax

It has the following syntax:

Example

type variable = new type(parameter_list);

In this syntax,

  • type: It represents the datatype of the variable for which the memory is allocated by the new operator.
  • new: It is an operator that is used to allocate the memory.
  • variable: It is the name of the variable thacpp tutorials to the memory.
  • parameter_list: It is the list of values that are initialized to a variable.
  • C++ new Operator Example

Let's consider an instance to demonstrate the new operator in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

int main() {  //main function

    // Dynamically allocate memory

    int* ptr = new int;

    // Assign a value

    *ptr = 15;

    // Print the value

    cout << "The value stored at ptr is: " << *ptr << endl;

    return 0;

}

Output:

Output

The value stored at ptr is: 15

Explanation:

In this illustration, we showcase the implementation of the new operator in C++. Initially, we instantiate a new integer to reserve memory for a single integer. Subsequently, assigning *ptr = 15 stores the specified value in the allocated memory. Ultimately, the program displays the resulting output.

What is the delete Operator in C++?

The delete operator in C++ is a fundamental operator utilized for releasing dynamically allocated memory. It is primarily employed for deallocating memory assigned to pointers created with the new operator or NULL pointer.

Syntax

It has the following syntax:

Example

delete pointer_variable;   // For single variables

delete[] pointer_variable;

C++ delete Operator Example

Let's consider a scenario to demonstrate the use of the delete operator in the C++ programming language.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

int main() {   //main function

    int* arr = new int[6];  // Dynamically allocate an array

    for (int i = 0; i < 6; i++) {

        arr[i] = i + 1;

    }

    cout << "Array elements are : ";

    for (int i = 0; i < 6; i++) {

        cout << arr[i] << " ";

    }

    delete[] arr;  // Deallocate array memory

    return 0;

}

Output:

Output

Array elements are : 1 2 3 4 5 6

Key Differences between new and delete Operators in C++

There exist several key distinctions between the fresh and erase operators in C++. Some primary variances are outlined below:

Definition

The fresh operator is primarily employed to reserve memory for an object or a collection of objects. It provides a pointer to the reserved memory. Conversely, the erase operator is primarily used to free up memory that was previously reserved with new. It frees the memory pointed to by the pointer and assigns null to the pointer.

Syntax

The syntax for the new operator is:

Example

pointer_variable = new data_type;

The syntax for the delete operator is:

Example

delete pointer_variable;

Allocation of memory

In C++, the new operator reserves memory from the heap for an object or an array of objects. This heap is a shared memory space. The size of the memory block is determined by the data type of the object or the array of objects. Conversely, the delete operator releases the memory that was initially reserved by the new operator.

Initialization

In C++, the new operator sets up the memory allocated for an object using the default class constructor. If a default constructor is absent, the placement new operator can be used to invoke the appropriate constructor. On the other hand, the delete operator does not handle any initialization tasks. It solely invokes the destructor of objects and frees up the allocated memory.

Allocation of array

In C++, the new keyword is commonly used to dynamically allocate memory for an array of objects.

Syntax

The syntax for array allocation is:

Example

pointer_variable = new data_type[array_size];

Conversely, the delete operator can be employed to free up memory previously allocated for an array of objects using the new operator.

Syntax

The syntax for array deallocation is:

Example

delete[] pointer_variable;

Exception Handling

In C++, when the new operator encounters a failure in memory allocation, it has the ability to throw an exception. Should this occur, the program has the option to handle the exception appropriately. On the other hand, the delete operator does not raise any exceptions when deallocating memory.

Operator Overloading

In C++, it is possible to overload both the new and delete operators, enabling customization of dynamic memory allocation and deallocation processes for individual classes. This capability proves beneficial in various scenarios, including debugging, memory pooling, and developing bespoke memory management mechanisms.

Global Overload

In C++, it is possible to globally overload the new and delete operators to modify how memory is allocated and deallocated within the program.

New Operator Syntax

The format for overloading the global new operator is outlined below:

Example

void* operator new(size_t size);

Delete Operator Syntax

The format for overloading the global delete operator is outlined below:

Example

void operator delete(void* ptr);

By implementing custom functionality in these operators, we can tailor the memory assignment and release process within the software. This capability proves invaluable in various scenarios, particularly when working on projects like real-time applications and embedded systems.

Difference between new and delete Operators in Tabular Form

Several key variances between the new and delete operators in C++ are outlined as follows:

Features New Operator Delete Operator
Definition It allocates memory for an object or array of objects. It deallocates memory allocated by new.
Syntax pointervariable = new datatype; delete pointer_variable;
Memory Allocation It allocates memory from the heap. It frees memory allocated by the new operator.
Initialization It initializes memory with the default constructor. It does not perform any initialization process.
Array Allocation It allocates memory for an array of objects. It deallocates an array of objects.
Exception Handling It can throw an exception if it fails to allocate memory. It does not throw any exceptions.

Conclusion

In summary, the new and delete operators play a crucial role in managing dynamic memory. While both operators work with heap memory, they differ in syntax, usage, and initialization behavior. Familiarizing ourselves with these operators enables us to effectively address issues like memory leaks and enhance our management of system resources.

Difference between New and Delete Operator FAQs

1) What is the new operator in C++?

The new operator dynamically reserves memory on the heap for objects or arrays of objects.

2) What is the delete operator in C++?

The delete operator frees up the memory that was previously allocated by the new operator for a specific object or variable.

Calling the delete operator twice on the same pointer causes undefined behavior. This can lead to memory corruption, crashes, or other unpredictable outcomes. It is important to only delete memory once and set the pointer to null afterward to avoid such issues.

If we invoke the delete operator repetitively on a single pointer, it can result in undefined behavior and cause the program to crash.

4) Is it possible to overload the new and delete operators in C++?

Yes, it is possible to override the new and delete operators within a class in order to personalize the allocation and deallocation of memory.

5) How does the usage of 'delete' differ from 'delete' in C++?

The delete operator is primarily used to free up the memory for a single object. On the other hand, the delete operator is mainly employed to release the memory for an array of objects allocated using new.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience