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:
- The compiler checks if the type is a class type or an array type.
- If it's a class type, the compiler calls the constructor of the class to initialize the object.
- If it's an array type, the compiler initializes each element of the array to its default value (e.g., 0 for integers).
- 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
:
- Memory leaks: If you forget to delete the memory, it will remain allocated and cause memory leaks.
- Dangling pointers: If you delete the memory and then try to access it, you'll get a dangling pointer error.
- Double deletion: If you delete the memory and then try to delete it again, you'll get a runtime error.
To avoid these issues, make sure to use new
and delete
carefully and consistently, and consider using smart pointers instead.