When to use new and delete in c++?

Asked

Viewed 74 times

0

I’m studying on pointers in c++, I still don’t quite understand how to use but I already have a notion, and one of the utilities I’ve seen is "dynamic allocation". I’ve heard of it in C language with malloc() and free(), but I did not find any content in Portuguese speaking of new and delete (I saw in English, but my English is not yet of this level)

My doubts are: How it works new and delete? And when to use?

2 answers

0

Basically, new and delete are a safe alternative to direct use of malloc() and free().

new and delete are casings (Wrappers) from C++ to malloc() and free(), That is, underneath the scenes they use these functions and add some treatments to them. Among the treatments are the guarantee of a safe operation, preventing access to locations of invalid memory, and ensure that the return will not be null (case malloc() return null, new will launch a Exception).

-1

With the operator new we can initialize the value or allocate memory in Runtime.

int *a = new int(25);
int *b = new int[10];

The variable stays in memory until do delete.

delete a;
delete[] b;

Dynamic allocation allows us to define arrays of variable size.

void foo(int size) {
    int* c = new int[size];
    ...
    delete [] c;
}

If we do not use this method the memory is allocated in the compilation and is out of scope if we leave the function. We should use only when necessary to avoid memory Leaks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.