Hacktoberfest 2026:メンテナが10月に向けて印を付けた、オープンで初心者向けの issue。 Hacktoberfest の issue を見る

Guideline for how to declare variables in a range-based for loop

オープン
#2,115 コメント 5 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
25/100
issue の種類
ドキュメント
明瞭さ
おおむね明確
活発さ
停滞
技術スタック
cpp
領域
documentation

調査の方向性

まず、既存の Con.1 と ES.71 のガイダンス、およびこの issue に寄せられた 5 件のコメントを確認します。提示されたルールが、引用されている range-based-for のケースを含め、それらの推奨事項を置き換えるべきか、明確化すべきかを判断します。完了とは、決定に達し、合意したガイダンスを C++ Core Guidelines の関連セクションに記録することです。

索引モデルが issue の本文から書いたものです。

説明

A question which comes up every now and then is what type of loop variable you should use for range-based for, particularly when no mutation takes place.

// case (1) - cheap to copy
for (int x : container) // disallowed in this form by Con.1, should be 'const int'
// vs
for (const int &x : container)
// case (2) - expensive to copy
for (string x : container) // disallowed in this form by ES.71, should be 'const string &x'
// vs
for (const string &x : container)

I think we should recommend to always declare the loop variable as a reference, never as a value, and here's why:

  1. The rule is simple and consistent.
  2. When mutating a T& variable in the loop, you are already forced to follow it by the language.
  3. If you aren't, and you have case (2), then ES.71 already tells you to.
  4. Otherwise, if you are following Con.1, then const T x is only one character away from const T &x, so it costs very little effort to follow this rule.
  5. It is possible and relatively easy to enforce with automatic tooling.
  6. It prevents bugs related to taking the address of the local variable, instead of taking the address of the object within the container.
  7. Even for weird iterators like std::ranges::iota_view::iterator, where their reference is actually a value, this method is robust because const& allows for temporary materialization.

In essence, I don't see any benefit to non-reference loop variables, and the alternative is consistent, easy, correct by default, and already recommended in part.

主要言語
CSS
スター
45.3k
フォーク
5.6k
PR マージ指標
30日以内にマージされた PR はありません

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

isocpp/CppCoreGuidelines のほかの issue

isocpp/CppCoreGuidelines の issue をすべて見る

似ている issue

Documentation の issue をもっと見る

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

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