1

I've learned some guidelines that all told me pass a variable by reference should always use const, like func(const T& a). And I know the second template parameter in CList is a ARG_TYPE. Like CList::AddTail(ARG_TYPE item) would use ARG_TYPE as its parameter type.

I saw the sample codes in msdn shows me it uses the non-const Type as its second template argument. Any reasons to prefer this non-const Type as parameter type?

CList<string, &string> a; vs CList<string, const &string> b;

Any suggestion would be helpful. Thanks.

4

1 に答える 1

4

const なしで C++ をプログラミングすることは、安全ベルトを着用せずに運転するようなものです。

1.変更を意図していない変数の変更から保護します。

2.偶発的な変数の割り当てを防ぐ

3. const 参照によって引数を受け入れると、値渡しの安全性を備えた参照渡しの効率が得られます

同時に、変数/関数の状態が常に正確にわかっているため、コンパイラはより効率的なコードを生成できます。タイトな C++ コードを作成している場合は、これで十分です。

参考までに、この記事で const の不便さを読みましたが、const-correctness を使用することを強くお勧めします

http://duramecho.com/ComputerInformation/WhyHowCppConst.html

于 2014-04-22T04:50:22.837 に答える