News for hackers. Stuff that matters.
Re:Why Const Sucks by kazinator on Monday March 05, 2018 @09:02PM (#16526325)
> Now, Java also added a number of nice things that C++ didn't have - such as an array knowing its own length, array bounds checking, and other features geared towards protecting the programmer from stupid mistakes.

C++ has bounds-checked arrays that know their length if you want (hello, std::vector<T>, or roll your own if you don't like that one). It just doesn't endow the C arrays with it (for good reasons). The C compatibility of C++ means that C++ interoperates easily with C API's without the overhead of FFI.

Re:Why Const Sucks by gurkendoktor on Tuesday March 06, 2018 @04:31PM (#16532277)
I assume the author refers to "T *t = new T[x]", which probably predates and inspired Java.

There is no reason why C++ can't provide a lengthof(x) function that returns the length of arrays allocated using new[], since the length needs to be stored internally anyway -- otherwise delete[] wouldn't know how many destructors to call. It would also be great if there was a realloc() equivalent that did the right thing with regards to constructors/destructors, because it's not possible to build this functionality on top of C's realloc().

new[] and delete[] are frustrating. If you "typedef int X[5]", how do you correctly free one instance of X - "delete new X" or "delete[] new X"?

The problem is that vector<T> isn't great either. Only C++03 made it legal to assume that vector<T> has contiguous storage (which is critical when interfacing with C APIs), and only C++11 made it possible to transfer vectors without expensive copies. But using rvalue references and copy elision correctly is certainly not trivial, and using vector<T> as a building block for your own data structures is in some ways more frustrating than using new[].

I think C++ should deprecate new[] and delete[], add a library function std::realloc_array<T>(ptr_or_null, length) that can be used to replace new[]/delete[]/realloc() and another library function std::array_length(ptr), and then vector<T> and other data structures could be built on top of that with little overhead. But I don't see it happening.

Re:Why Const Sucks by satish-setty on Tuesday March 06, 2018 @12:53AM (#16527141)
There is std::array<T, N> in modern C++ standard. It is meant for static arrays which know their own length.

http://en.cppreference.com/w/cpp/container/array

Re:Why Const Sucks by beojan on Tuesday March 06, 2018 @04:43AM (#16527870)
Well... .at() is bounds checked, but operator[] (which is what most people use) isn't.

It should probably have been the other way around, I'd say.