C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Draft 2: Error on out-of-bounds index

From: Oliver Hunt <oliver_at_[hidden]>
Date: Fri, 29 Aug 2025 16:16:36 -0700
> On Aug 29, 2025, at 2:43 PM, Levo D via Std-Proposals <std-proposals_at_[hidden]> wrote:
>
> The goal of my proposal is to have all bounds be checked at compile time. If I were including containers, the check would be for all containers (and arrays).
> I haven't seen "hardened preconditions," but glancing at P3471R0, it looks like it's a runtime check, which isn't my goal.

If the bounds and index are known constants at runtime the will be removed. If the bounds and/or index are not known/guaranteed the check _must_ be at runtime. That’s fundamentally unavoidable.

> There isn't anything I could add to that. It'd be helpful if that proposal went through, since there might be a lot of changes inside a code base for access to be provably in bounds.
> Off the top of my head, there might not be too many changes in my current one and one for containers.

It sounds like what you want is a _dianostic_ for trivial cases, which is already present in clang (it’s a warning by default, but you can turn it into an error with -Werror=array-bounds).

Slices as you’re proposing aren’t like to happen because the path to memory safety requires moving away from C arrays and pointers as they simply do not have bounds information, and in most cases the information available can't be relied on - this is why despite their best efforts -fbounds-safety can easily require quite a lot of annotations.

The correct thing to do is use things like std::span and similar.

> The harder part is stating when a container shouldn't have a bounds check (unless I should explicitly name all the containers that should have it).

No - if you know the bounds of an object it is _always_ broken to access out of the bounds.

> A map where people may want mapVar[-123] to return a value shouldn't be checked,

I’m not sure what you mean? Do you mean std::map<int, ..> or similar? There would not be a bounds check for that: it’s a map, not an array?

> although I'm unsure if people want me to include a case for maps where we need to check if a key exists before using it that way.

It is indeed somewhat annoying that operator[] does not really have a good way to distinguish reading vs writing, so your choice is implicit creation of an entry that may not be written to (resulting a key being present but not written, etc), a fairly exciting proxy, or triggering some kind of error.

But this is not bounds checking - the range of the key is not relevant.

—Oliver

> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2025-08-29 23:17:08