When to allocate memory dynamically?

In C++ you can easily declare an object or variable like this:

tipo_da_variável nome_da_variável;

This type of statement is the easiest to use, but you can also use new to dynamically allocate memory and then deallocate with delete.

Is it true that dynamically allocating objects makes the program faster, that is, makes it occupy less memory and CPU?

Should I always dynamically allocate objects?

If the answer to these 2 questions above is no, then could you exemplify some cases that the use of dynamically allocated memory is justifiable? Or explain to me what the utility of dynamically allocating memory?

I've heard that dynamically allocating memory is something that should be done when we don't know how much memory we'll need, but I also didn't get this argument right, after all my compiler accepts the code without errors:

int num1;
cin >> num1;
char palavra[num1];

In the code above, the size of the array will depend on the value that the user type, ie start, we do not know how much memory the program will use and even then, it was not necessary to use new + delete

Author: Maniero, 2018-04-17

1 answers

tipo_da_variável nome_da_variável;

This type of statement is the easiest to use

Yes, but it's wrong. Not initializing a value is an error.

This form is called automatic allocation.

It is true that dynamically allocating objects makes the program faster

No, in general it is the opposite, one should avoid dynamic allocation as much as possible, without causing other problems.

Does it take up less memory and CPU?

Are things but dynamic allocation will always consume more memory, invariably. The work to allocate is often monumental compared to automatic allocation. And if it is not, the release will be monumental. You can't categorically state why C and C++ let you manage memory in different ways.

Should I always dynamically allocate objects?

No, it's much more complicated to manage this.

Could exemplify some cases that the use of is dynamically allocated memory justifiable?

I think this is already answered in several questions:

After all my compiler accepts without errors the Code

Working is different from being right.

Car Fiat 147 falling to pieces trafficking through the streets

In the above code, the size of the array will depend on the value that the user enters, that is, from start, we do not know how much memory the program will use and even so

No problem, can do automatic allocation set at runtime, this does not make the allocation be dynamic.

 4
Author: Maniero, 2020-07-17 12:32:19