c++arraysdynamic-memory-allocationstatic-memory-allocation

Are 'new' and 'delete' getting deprecated in C++?


I stumbled upon a quiz that involved array declaration with different sizes. The first thing that came to my mind is that I would need to use dynamic allocation with the new command, like this:

while(T--) {
   int N;
   cin >> N;
   int *array = new int[N];
   // Do something with 'array'
   delete[] array;
}

However, I saw that one of the solutions allowed the following case:

while(T--) {
    int N;
    cin >> N;
    int array[N];
    // Do something with 'array'
}

After a bit of research I read that g++ allows this, but it kept me thinking, in which cases is it then necessary to use dynamic allocation? Or is it that the compiler translates this as dynamic allocation?

The delete function is included. Note, however, that the question in here is not about memory leaks.


Solution

  • Well, for starters, new/delete are not getting deprecated.

    In your specific case, they're not the only solution, though. What you pick depends on what got hidden under your "do something with array" comment.

    Your 2nd example uses a non-standard VLA extension which tries to fit the array on the stack. This has certain limitations - namely limited size and the inability to use this memory after the array goes out of scope. You can't move it out, it will "disappear" after the stack unwinds.

    So if your only goal is to do a local computation and then throw the data away, it might actually work fine. However, a more robust approach would be to allocate the memory dynamically, preferrably with std::vector. That way you get the ability to create space for exactly as many elements as you need basing on a runtime value (which is what we're going for all along), but it will also clean itself up nicely, and you can move it out of this scope if you want to keep the memory in use for later.

    Circling back to the beginning, vector will probably use new a few layers deeper, but you shouldn't be concerned with that, as the interface it presents is much superior. In that sense, using new and delete can be considered discouraged.