C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Contracts: Observe semantic and multiple preconditions

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Fri, 25 Aug 2023 00:56:58 +0300
On Fri, 25 Aug 2023 at 00:52, joegottman--- via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> I just read the most recent record of contract support (P2521R5) and I have a question about the new possible "observe semantic" for contracts. As I understand it, this means that after a contract violation the program invokes a contract violation handler that presumably logs the failure, and then continues. But what happens if there are two or more preconditions and the first one fails? Will the second precondition be checked? That could cause problems in the case of code like the following:
>
> int foo(int *p) [[pre: p != nullptr]] [[pre: *p > 0]];
>
> If foo(nullptr) is called the first precondition will fail and be logged. If the program then attempts to check the second precondition then it will attempt to dereference the null pointer and crash.

Right. Don't do that. Write

int foo(int *p) [[pre: p]] [[pre: p && *p > 0]];

instead. Or use a predicate function for the second precondition, and
throw an exception if p is 'still' null.

Received on 2023-08-24 21:57:12