4 ms·
Not if you stick with the ::at() method, which does bounds checking https://en.cppreference.com/w/cpp/container/vector/at https://en.cppreference.com/w/cpp/con
by patrick451 4y ago
Not if you stick with the ::at() method, which does bounds checking
https://en.cppreference.com/w/cpp/container/vector/at https://en.cppreference.com/w/cpp/container/vector/at
- agwa 4y agoUnfortunately, std::span doesn't have at(). Note that std::vector's at() predates C++11, whereas std::span was added in C++20. It's a myth that C++ is getting more memory-safe; in many aspects it's actually regressing.
- kazinator 4y agoRegardless of all that, you can make your own vector class which works exactly how you want and is completely safe. In a greenfield project where you control every line of C++ code, you can easily achieve very good safety using nothing but ancient C++ features. Not just memory safety. I mean, you can make your own numeric types that do overflow checks and throw exceptions or whatever. It probably won't be very fast, but it will be solid. People have used C++ (ancient C++) to make numeric types with units, where you can't add "kilograms per second" to "meters". I remember that from some talk thing I went to in 1999.
- LaLaLand122 4y agostd::span doesn't have at() because std::logic_error was a mistake. Using std::vector's at() is a mistake (you could use it as a helper method and make it as if it throwed std::runtime_error, but it doesn't, that wasn't its intended usage). All three major C++ standard library implementations have an option to enable assertion checks in both std::vector and std::span operator[]. Enable them unless you are in such a resource limited environment that you can't afford the checks (unlikely). The only reason the standard doesn't require the checks is to allow C++ to be usable in those resource limited environments. You could argue the checks should be enabled by default, but that's not something for the standard to decide, complain to your standard library vendor.
- int_19h 4y agoIt's not just the indexing you have to worry about, though. It's also out-of-bounds iterators. And while, yes, you can tell your implementation to emit checks for those as well, it's so slow in practice that nobody uses it in optimized release builds (and some implementations don't even support such use).
- LaLaLand122 4y agoSure. I agree. I was just arguing that it's good span doesn't have at(), I was not trying to say C++ is memory safe.