Question

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.

Was it helpful?

Solution

Programming C++ without const is like driving without the safety belt on.

1.It protects you from changing variables that aren't intended be changed,

2.It protects you from making accidental variable assignments

3.Accepting arguments by const reference gives you the efficiency of passing by reference with the safety of passing by value

At the same time, the compiler can generate more efficient code because it knows exactly what the state of the variable/function will be at all times. If you are writing tight C++ code, this is good.

Just for your reference I have read Inconveniences of const in this article, but its higly recommended to use const-correctness

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top