4 ms·
This is just standard C++isms. You can get a reference to an item in a std::vector with the [] operator as you would with an array in many other languages. It
by furgooswft13 8y ago
This is just standard C++isms.
You can get a reference to an item in a std::vector with the [] operator as you would with an array in many other languages. It does not do bounds checking, as specified in documentation. Trying to access an out of range element is undefined behavior.
Or you can use the .at() method, which will throw an exception if you go out of bounds. It is the programmer's choice.
Bounds checking is not free, same with checking for a null pointer. C++ is a performance oriented language so it gives you the choice to play it a little unsafe in the name of having full control.
I understand the idea to want the language to make it more obvious that you are doing something potentially unsafe, but it has never been the case in C or C++ that dereferencing a pointer is considered 'safe'.
You have to know what you are doing, else you might end up blowing your whole leg off [1].
[1] https://www.goodreads.com/quotes/226222-c-makes-it-easy-to-shoot-yourself-in-the-foot https://www.goodreads.com/quotes/226222-c-makes-it-easy-to-s...
- Gaelan 8y agoI guess I don't know why you'd even want an optional if it wasn't for the safety. Without compiler-enforced null checking, I don't see why you'd want one.
- furgooswft13 8y agoC++ already has compiler-enforced null checking by virtue of not allowing non-pointer variables to be null. But sometimes we want a variable to be null and not be a pointer. Consider: struct stuff { int required_value; int optional_value; } What would you do if you had no value for optional_value? Probably use 0 or -1 but that can be problematic, and not even an option if optional_value is not a primitive type. You could use int* optional_value instead and just assign NULL, but then you have to malloc/new and make sure to free/delete later. You could use std::unique_ptr to handle memory management but you are still invoking dynamic memory. std::optional allows you to have nullable variables without using pointers, even when hidden behind the scenes. You could ask, what is the point of optional if you don't want to check if it is null? Well...I guess it's the same as no bounds checking, sometimes the programmer just knows. Most of the time, hopefully, a check will be done at some point, and subsequent accesses can skip the check.
- Gaelan 8y agoSo I guess C++'s optional type is for a completely different purpose from other languages, which is why I think I was confused.