C++ Logo

std-proposals

Advanced search

Re: [std-proposals] noexcept(static)

From: Thiago Macieira <thiago_at_[hidden]>
Date: Thu, 17 Sep 2026 07:47:51 -0700
On Thursday, 17 September 2026 03:36:30 Pacific Daylight Time Frederick
Virchanza Gotham via Std-Proposals wrote:
> 'sqrt' is a bad example because it has a wide contract -- you're allowed to
> give it a negative number without inducing UB.

It's still a good example by being a wide contract function with no "noexcept"
marker in most libcs. That would mean you can't call it in your
noexcept(static) functions because it isn't declared to never throw.

> Let's talk about 'std::vector::operator[]' instead. If you give it an
> invalid index, you get UB. Because of the Lakos rule, it's marked
> 'noexcept(false)'.
...
> The above will unfortunately fail to compile. So I think what we want is
> something like:
>
> int &Monkey( vector<int> &v, size_t const n ) noexcept
> {
> static_assert( noexcept_if_unhardened( v[n] ) );
> return v[n];
> }


Ongoing discussion

P1656 - "“Throws: Nothing” should be noexcept"
P2831 - "Functions having a narrow contract should not be noexcept"

Join it by publishing your paper arguing. I don't think a new syntax helps.

I am in the camp of P1656: outside of unit-testing the implementation itself,
throwing an exception in a precondition violation is not useful, because the
situation is almost always unrecoverable. Exceptions can be caught, and that
might lead some misinformed developer to attempt to recover something they
shouldn't.

But even if my preference were adopted, it wouldn't be 100% and it probably
wouldn't apply to C libraries.

> So then maybe we should have:
>
> value_type &vector::operator[](size_t) noexcept_if_hardened(false)
> noexcept_if_unhardened(true);
>
> Maybe.... ? Just mulling through a rumination of ideas here . . .

That's just a macro.

-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel Data Center - Platform & Sys. Eng.

Received on 2026-09-17 14:48:01