Dynamic memory allocation and release
In C++, we can use the keywords new
and delete
to allocate and release dynamic memory. Dynamic memory allocation allows us to create and use memory on demand while the program is running, which is very useful for dealing with dynamic data structures and flexible memory management.
Dynamic memory allocation using new
The keyword new
can be used to dynamically allocate memory space for a single object. Here's new
an example of creating a single object using:
int* p = new int; // 分配一个 int 类型的内存空间,并将指针 p 指向该空间
In the above example, new int
a memory space of type is allocated int
and a pointer to that space is returned. Pointer p
is used to store the pointer value.
Instead of allocating a single object, we can also new
allocate an array of objects using . Here's new
an example of creating an array of objects using:
int size