cpp-best-practices / cpp-best-practices/cppbestpractices

Const as Much as Possible (Not!)

Offen
#128 3 Kommentare 3 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
Vorherrschende Sprache
Keine Sprachdaten
Sterne
8.8k
Forks
902
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

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.)

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Rechercherichtung

In der Issue wird keine Datei und kein Test genannt. Beginne damit, den Best-Practices-Abschnitt zu finden, der const-Funktionsparameter behandelt, und vergleiche dann dessen Hinweise mit den C- und C++-Beispielen im Bericht; als erledigt gilt es, wenn die Dokumentation die direkte constness von Parametern klar von der constness der Daten unterscheidet, auf die gezeigt wird.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
cpp
Bereich
documentation
Issue-Typ
Dokumentation
Schwierigkeit
2/5
Geschätzter Aufwand
1-3 Stunden
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.