5 ms·
std::vector is bounds checked if you use .at() instead of operator[]. But it's less ergonomic and I don't think people typically use that.
by im3w1l 3y ago
std::vector is bounds checked if you use .at() instead of operator[]. But it's less ergonomic and I don't think people typically use that.
- kbolino 3y agoGood point. I would think you could make operator[] bounds-checked with an opt-in mechanism like a #define but I don't know if such a thing exists and I would assume it could cause unpredictable behavior in code not designed to handle exceptions. Thinking about this example, it seems like the other problem is that even when bounds-checked, C++ code handles out-of-bounds conditions by throwing exceptions, which seem to have a bad rap in C++.
- gpderetta 3y ago_GLIBCXX_ASSERTIONS which is explicitly intended to be enabled for production builds.
- im3w1l 3y agoI actually disagree with that. Exceptions have their problems when used for error handling, but they are a great solution for error not-handling, and normally index out of bounds is a bug that you can't / don't want to recover from. Exceptions will bubble up and unwind the stack, cleaning things up by running destructors. In other languages they will also display a nice little backtrace, though in c++ it seems thats not typically done for reasons that are beyond me.
- kbolino 3y agoYeah, I've got more experience lately with Go and Rust, where as you say, error not-handling is an acceptable fallback for unintentional mistakes via panic. I'm not sure what the practical differences are between C++ exceptions and Rust/Go panics though, apart from the lack of backtrace.
- gpderetta 3y agoOr you if you flip the correct compiler flags.