3 ms·
> incorrect array access would lead to a runtime exception, whereas in C++ this leads to incorrect memory access or memory corruption in case of writing. Which
by adhesive_wombat 5y ago
> incorrect array access would lead to a runtime exception, whereas in C++ this leads to incorrect memory access or memory corruption in case of writing.
Which is why the STL gives you std::array with a bounds-checked accessor (at()).
If you haven't checked your bounds, use that and handle the exception.
If you use a C-style array, expect C-style memory safety.
- pjmlp 5y agoAdditionally all modern C++ compilers have compiler options to also enable bounds checking in operator[](), which should be taken advantage of.
- hoseja 5y agoThis is one of major faults with C++; the simpler, more elegant syntax is unsafe-by-default due to backwards compatibility.
- pjmlp 5y agoTrue, however how else would Bjarne have sold C++ to C folks, just dive into the Usenet archives to see the flame wars of the time and people counting CPU cycles per language feature. The same can be told about TypeScript, no matter how good its type system is, it will never prevent JavaScript gotchas, for similar reasons.
- tialaramex 5y agoI don't think std::array is from the Template Library but is instead simply a type provided by the C++ standard library itself. Accordingly it isn't a great fit for the STL's container concept and has to be special-cased. Also, once again bad defaults in C++. The default array accessor should be bounds checked. If I'm quite sure I wish to risk unchecked access that is an explicit decision signified by using a different accessor. This is the same mistake as discussed below for integer overflow, if the programmer doesn't specify a non-default behaviour that doesn't mean they spent ages agonising over the fine details of whatever the default behaviour happens to be, it means they didn't realise it mattered. Accordingly obey the principle of least surprise and don't do crazy things by default.
- pjmlp 5y agoWhile the defaults isn't what security minded folks would wish for, ISO C++ doesn't prevent a compliant implementatio to have them bounds checked, as such all major C++ compilers do provide compiler options to enable all uses of operator[]() as bounds checked, including interator invalidation. In C++ circles although STL has long moved beyond its original purpose, most people do refer to the C++ standard library as STL.