Why both runtime-sized arrays and std::dynarray in C++14?

不羁的心 提交于 2019-11-29 02:48:09

N3639 proposes to add local runtime-sized arrays with automatic storage duration to C++.

N2648 says that in keeping with C++ practice, std::dynarrays are usable with more than just automatic variables. But to take advantage of the efficiency stack allocation, we wish to make dynarray optimizable when used as an automatic variable.

In short, C11 style runtime-sized arrays are restricted to being stored on the stack. dynarray is not, but can be optimized when stored on the stack to be as efficient as C11 style runtime-sized arrays (or so is the goal).

C11 style runtime-sized arrays can be a useful syntax still, and the cost to increase intercompilability with C isn't high: the mechanism would have to be implemented for efficient automatic dynarray anyhow. In addition, C11 style runtime-sized arrays are first class citizens, and exist regardless of use of std libraries by the programmer.

There are important differences between actual C11 runtime-sized arrays and C++1y C11-style runtime-sized arrays, not the least of which is the runtime sizeof that actual C11 runtime-sized arrays support. But basic use of it may be compatible.

Note that in the end, neither where added in C++14.

I think you answered the question yourself, std::dynarray has the stl interface. A goal of c++11 and I'm assuming c++14 is to make c++ more user friendly, less error prone and easier for beginners. With c style arrays you may run into pointer arithmetic problems but dynarray avoids the problems if used as intended
EDIT: so it looks like one difference is that runtime-sized arrays must be allocated on the stack, increasing the likelyhood of a stack overflow. dynarray is allocated on the heap though it is possible to allocate on the stack (if the implementation did so)

sasha.sochka

As you said yourself std::dynarray will provide STL-style interface, which makes it more idiomatic to use. Still, C++ needs dynamic arrays created with new[] to:

  1. at least implement std::dynarray (so you can't have dynarray without new[])
  2. retain compatibility with previous versions

You can not just say that all code, which uses new[] is now wrong.

In general, the difference between C++14 std::dynarray and C++ new[] array is almost the same as difference between C++11 std::array and C-style arrays.

UPD: Now I see you are now asking about feature similar to C11 (VLA's). Actually there is nothing to do with it - VLA's are very limited and you can use only an argument of the function as your array size. Also, memory is allocated on stack, but for std::dynarray memory is allocated in the heap. Basically, this feature just extends C-style arrays a little bit more and makes C++ a bit more compatible with modern C standard.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!