C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Efficient and silent bounds checking with silent_at()

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 5 Jul 2023 21:46:59 -0400
On Wed, Jul 5, 2023 at 9:35 PM trtaab trtaab via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Dear Proposal Forum,

This is not a letter; you don't need to preface everything with "Dear whomever".

> In response to your request for a clearer explanation of the proposed "silent_at" method and its significance, I would like to provide a concrete example to illustrate its implementation and compare it to the existing "at()" method.
>
>
>
> Consider the following example implementation of the "silent_at" method:
>
>
>
> inline constexpr T& silent_at(std::size_t index) noexcept
>
> {
>
> if (len <= index)
>
> {
>
> __builtin_trap(); // Program crash in a controlled manner
>
> }
>
> return ptr[index];
>
> }
>
> In this implementation, the "silent_at" method performs bounds checking by comparing the specified index to the length of the container. If the index is greater than or equal to the length, indicating an out-of-bounds access, the program crashes using __builtin_trap(). Since the method is marked as noexcept, the compiler is free to optimize it as needed, including reordering the trap.

So it's just an assert that doesn't go away in non-debug builds? I
don't know; this sounds vaguely like contracts to me.

Received on 2023-07-06 01:47:13