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

Const as Much as Possible (Not!)

オープン
#128 コメント 3 件 リアクション 3 件 担当者 0 名 GitHub で見る
主要言語
言語のデータがありません
スター
8.8k
フォーク
902
PR マージ指標
30日以内にマージされた PR はありません

説明

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

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。