r/cpp • • Jul 29 '26

C++26: Reducing undefined behaviour

https://www.sandordargo.com/blog/2026/07/29/cpp26-reduces-undefined-behaviour
89 Upvotes

48 comments sorted by

View all comments

Show parent comment

6

u/qoning Jul 29 '26

Classic "zero cost abstraction" misunderstanding in the wild. In this case, you are using the bounds check, so it's a zero cost abstraction either way.

-1

u/sessamekesh Jul 29 '26 edited Jul 29 '26

I'll copy my other comment. 

It can be, I personally wouldn't consider bounds checking to be part of the cost of a pointer dereference (which is, under the hood, what vec[k] is).

I have similar feelings about other things like zeroing out newly allocated memory. Safety might be the appropriate default and the correct thing to do 95% of the time, but you're certainly going to have outliers where the safety work (which is real even if trivial runtime cost) is redundant or otherwise undesirable.

If "you'd have to do it anyways" was a good defining property of a zero cost abstraction, you could call the entirety of a windowing layer like GLFW "zero-cost," which I find pretty silly.

EDIT: A contrived example for why runtime bounds checks should not be considered always appropriate:

std::vector<uint16_t> get_byte_frequency(const std::string& buffer) {
  std::vector<uint16_t> byte_counts(256, 0);
  for (const auto& c : buffer) {
    // Safe - size of buffer matches/exceeds width of underlying type.
    // Bounds checking here is unhelpful.
    byte_counts[c]++;
  }

  return byte_counts;
}

2

u/TheThiefMaster C++latest fanatic (and game dev) Jul 30 '26

This is why the current talk is on bounds checks that can be optimised out. This one can - the size is known, as is the range of a char, so it's easily determined to be superflous and removed.