3 ms·
You probably see this attitude a lot because of modern C++ features that do make it a lot easier to write safer code. However that is not absolute. Just the ot
by arsome 3y ago
You probably see this attitude a lot because of modern C++ features that do make it a lot easier to write safer code. However that is not absolute.
Just the other day I had used std::sort on and std::vector. Pretty simple stuff, figured there can't be a way to screw that up, but my app kept crashing in the sort call because it was trying to write past the end of the array. Turns out if your comparison function doesn't perfectly follow strict weak ordering sort will just blow the bounds of your array without checking.
- exikyut 3y agoFrom https://www.boost.org/sgi/stl/StrictWeakOrdering.html https://www.boost.org/sgi/stl/StrictWeakOrdering.html: > A Strict Weak Ordering is a Binary Predicate that compares two objects, returning true if the first precedes the second. This predicate must satisfy the standard mathematical definition of a strict weak ordering. The precise requirements are stated below, but what they roughly mean is that a Strict Weak Ordering has to behave the way that "less than" behaves: if a is less than b then b is not less than a, if a is less than b and b is less than c then a is less than c, and so on. So if I take it correctly, std::sort will happily ticker-tape your array into the nearby dragon's lair if the sort callback doesn't return -1/0/1 correctly? <Rueful mental note>
- account42 3y agoThe range of the return value is not the issue - the comparison function [0] for std::sort returns a bool and not a tristate anyway. What gp probably messed up is the one of the guarantees of a strict weak ordering: - Irreflexivity: comp(a, a) == false for all a - Transitivity: if comp(a, b) == true and comp(b, c) == true then comp(a, c) == true - Asymmetry: if comp(a, b) == true then comp(b, a) == false std::sort can assume that all these requirements are true and does not have to care about what happens if they don't. [0] https://en.cppreference.com/w/cpp/named_req/Compare https://en.cppreference.com/w/cpp/named_req/Compare
- exikyut 3y agoThanks very much for this :)