4 ms·
I had more bugs pop up from people calling front() on an empty vector than from direct out of range bounds. I guess people are more cautious when they are manip
by dureuill 4y ago
I had more bugs pop up from people calling front() on an empty vector than from direct out of range bounds. I guess people are more cautious when they are manipulating indices than when calling a method that takes 0 arguments?
Debug asserts are nice, but not sufficient when the code path causing the empty vec is only encountered by a production user from a different country at 2am. Enabling the asserts in release mode will at least prevent undefined behaviour and malevolent users from harming the system, but the best interface is the one that returns an optional, so as to make the "vector was empty" case explicit. That way it has a higher chance to be considered by the authors of the code or their reviewers.
- planede 4y agoWell, front() returns a reference. std::optional can't hold references. The closest you get is a plain pointer, with a null pointer for an empty container.
- dureuill 4y agoOther languages allow to return `Option<&T>`. That's what I'm using these days. I suppose a raw ptr is what I would use on C++ to model that case though, yes.
- planede 4y agoYeah, for some reason `std::optional<T&>` is cursed and can't get through standardization. People can't decide what should happen on assignment.
- dureuill 4y agoI guess a raw pointer is good enough an approximation in that case, it is just annoying that suddenly you can no longer use an optional because your type is a reference