C++ new and delete Operators

C++ new and delete Operators

new and delete are operators in C++ that allow for dynamic memory allocation and deallocation, respectively. Managing memory manually is a powerful feature of C++ but also requires careful management to prevent issues like memory leaks.

1. The new Operator:

The new operator is used to allocate memory on the heap for a variable of a given type and returns a pointer to the first byte of the block of memory.

Basic Usage:

int* ptr = new int; // Allocates memory for an int on the heap *ptr = 5; // Assigns 5 to the memory location 

Array Allocation:

int* arr = new int[5]; // Allocates memory for an array of 5 integers 

2. The delete Operator:

The delete operator is used to deallocate memory that was previously allocated by the new operator.

Basic Usage:

delete ptr; // Deallocates memory for the integer 

Array Deallocation:

To deallocate an array, you must use delete[]:

delete[] arr; // Deallocates memory for the array of integers 

Important: Always ensure you match your new and delete usage correctly. If you allocate a single object, use delete. If you allocate an array, use delete[].

3. Constructor and Destructor Calls:

When you allocate memory for objects (i.e., instances of classes), the constructor is called. Similarly, when you deallocate memory, the destructor is called.

class MyClass { public: MyClass() { std::cout << "Constructor called!" << std::endl; } ~MyClass() { std::cout << "Destructor called!" << std::endl; } }; int main() { MyClass* obj = new MyClass; // Constructor is called delete obj; // Destructor is called } 

4. Handling Allocation Failures:

In modern C++, if memory allocation fails, a std::bad_alloc exception is thrown. It's a good practice to handle these exceptions, especially in applications where memory safety and availability are critical.

try { int* myArray = new int[1000000000UL]; // Tries to allocate 1 billion integers } catch (const std::bad_alloc& e) { std::cerr << "Memory allocation failed: " << e.what() << std::endl; } 

5. Memory Leaks:

If you forget to delete memory that you've allocated with new, you'll have a memory leak. Memory leaks consume your program's memory until it's terminated, which can be a problem, especially for long-running applications.

Example of a Memory Leak:

int main() { int* leakyPtr = new int[10]; // Some code... // Forgot to delete the memory before exiting! } 

To prevent memory leaks:

  • Always pair a new with a delete or a new[] with a delete[].
  • Use tools like valgrind or static analyzers to check for memory leaks.
  • Consider using smart pointers (std::unique_ptr, std::shared_ptr) introduced in C++11, which automatically manage memory for you.

6. Rule of Three/Five and Memory Management:

When you're creating classes that manage dynamic memory, always remember:

  • If you define or delete a destructor, copy constructor, or a copy assignment operator, you probably need to explicitly define or delete the other two (Rule of Three).

  • With C++11 and later, this extends to the move constructor and move assignment operator (Rule of Five).

In summary, new and delete are fundamental to dynamic memory management in C++. They provide fine-grained control over memory but require careful management to avoid issues. Modern C++ introduces smart pointers, which simplify dynamic memory management and reduce the risk of memory leaks and other related issues.


More Tags

shiny background-attachment cross-browser soapui osx-lion maxdate fetch telerik-mvc docker-compose xml-deserialization

More Programming Guides

Other Guides

More Programming Examples