Are 'new' and 'delete' getting deprecated in C++?
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.
Your second examples uses variable length arrays (VLAs), which are actually a C99 (not C++!) feature, but nonetheless supported by g++.
See also this answer.
Note that variable length arrays are different from new
/delete
and do not "deprecate" them in any way.
Be also aware that VLAs are not ISO C++.
Neither snippet you show is idiomatic, modern C++ code.
new
and delete
(and new[]
and delete[]
) are not deprecated in C++ and never will be. They are still the way to instantiate dynamically allocated objects. However, as you have to always match a new
with a delete
(and a new[]
with a delete[]
), they are best kept within (library) classes that ensure this for you. See Why should C++ programmers minimize use of 'new'?.
Your first snippet uses a "naked" new[]
and then never delete[]
s the created array. That's a problem. std::vector
does everything you need here just fine. It will use some form of new
behind the scenes (I won't dive into implementation details), but for all you have to care, it's a dynamic array but better and safer.
Your second snippet uses "variable length arrays" (VLAs), a C feature that some compilers also allow in C++ as an extension. Unlike new
, VLAs are essentially allocated on the stack (a very limited resource). But more importantly, they are not a standard C++ feature and should be avoided because they are not portable. They certainly do not replace dynamic (i.e. heap) allocation.