isocpp / isocpp/CppCoreGuidelines

NR.5 Example, good | check_size adjustment

Open
#1,478 4 comments 0 reactions 1 assignee View on GitHub

@hsutter is already working on this.

Since Sep 5, 2019.

Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

Quick Link to NR.5

In the good example, we have the following contract check:

static size_t check_size(size_t s)
{
    // invariant check
    Expects(s > 0);
    return s;
}

The problem with this function is, that check_size(-1) does not throw as you’d expect only reading the contract.

I propose to implement exactly one of the two ideas below to fix this:
Idea 1: Change the check to Expects(s != 0);, as s cannot be negative, and thus be more expressive in what exactly is checked.
Idea 2: Change the type of s to a signed integer one, maybe ptrdiff_t or intmax_t, and cast s to size_t after the check. (Alternatively, change to type of Picture::mx and Picture::my altogether.)

The latter approach has the advantage that calling Picture picture(100, -1); does not try to allocate excessive amounts of memory. On the other hand, the constructor would have to change, too, and a compiler should warn about the signed/unsigned mismatch anyway …

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.