course content

Course Content

Introduction to C++

New and DeleteNew and Delete

new

The new operator allows us to allocate a certain amount of memory on the fly. Let's allocate 4 bytes:

The code will compile, but we won't get anything from it, because the new operator returns the address of the allocated memory. To use this memory, the address must be stored somewhere. Here we need pointers!

Now let's use the allocated memory to store the number 200 there:

Let's display the number 200 on the screen through the pointer:

cpp

main.cpp

When you dynamically create a variable, you can initialize it explicitly, that is, lines 8 and 9 can be replaced with one:

Note

The C++ language does not have a garbage collector, which is why the programmer must free the occupied memory manually.

delete

After we have used the allocated memory, it should be cleared using the delete operator:

cpp

main.cpp

In fact, the delete operator does not delete, but returns the allocated memory back to the system. The C++ language makes no guarantees about what will happen to the contents of the freed memory.

A pointer that points to memory freed by the delete operator is called a dangling pointer. Trying to dereference or access memory through a dangling pointer will produce unexpected results:

cpp

main.cpp

So that the remote pointer does not interfere with us, it must be made null using the nullptr.

Section 6.

Chapter 4