Const as Much as Possible (Not!)

Open
#128 3 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
35/100
Issue type
Documentation
Clarity
Mostly clear
Activity status
Stale
Tech stack
cpp
Domain
documentation

Research direction

No file or test is named in the issue. Start by locating the best-practices section covering const function parameters, then compare its guidance with the C and C++ examples in the report; done means the documentation clearly distinguishes direct parameter constness from constness of pointed-to data.

Written by the indexing model from the issue text.

Description

While "Const as Much as Possible" is generally good practice, const should not be directly used on function declaration parameters, including member functions.

A quick example:

void foo (int x);
void foo (int const x) {return x * 2;}

void bar (char const * s);
void bar (char const * const s) {puts(s);}

Notice I said "directly". Hence s isn't const in the declaration, but is in the definition (direct), but what s points at is const in both, and must match in both (indirect).

The reason for doing this is to not leak a function's implementation details. Because whether a function treats a parameter variable as const or not is an implementation detail of the function. And if a function gets modified such that its parameter is no longer treated as const, then callers of that function shouldn't have to be recompiled.

This is a difference between C and C++. In C, the function definition's parameter type(s) must exactly match that of the function declarations. (At least it used to. I haven't actually developed anything significant with modern C.)

Dominant language
No language data
Stars
8.9k
Forks
901
PR merge metrics
No merged PRs in 30d

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

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.

More from cpp-best-practices/cppbestpractices

All issues in cpp-best-practices/cppbestpractices

Similar issues

More Documentation issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.