C++ new

The new keyword in C++!

new is a keyword in C++ 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 block of memory that is large enough to hold the object or array you want to create.

Here's the basic syntax:

Type* ptr = new Type();

Where Type is the type of the object or array you want to create, and ptr is a pointer to the newly allocated memory.

For example:

int* p = new int; // allocate memory for a single int

Or:

int* arr = new int[5]; // allocate memory for an array of 5 ints

When you use new, the following happens:

  1. The compiler checks if the type is a class type or an array type.
  2. If it's a class type, the compiler calls the constructor of the class to initialize the object.
  3. If it's an array type, the compiler initializes each element of the array to its default value (e.g., 0 for integers).
  4. The compiler returns a pointer to the newly allocated memory, which is stored in the ptr variable.

You can also use new to allocate memory for an array of objects:

MyClass* arr = new MyClass[5]; // allocate memory for an array of 5 MyClass objects

When you're done using the memory, you need to delete it using the delete keyword to avoid memory leaks:

delete p; // delete the single int
delete[] arr; // delete the array of ints

Note that new and delete are not the only ways to manage memory in C++. You can also use smart pointers, such as unique_ptr and shared_ptr, which provide automatic memory management and help prevent memory leaks.

Here are some common pitfalls to watch out for when using new:

To avoid these issues, make sure to use new and delete carefully and consistently, and consider using smart pointers instead.