Effective C++ Item 3 Use const whenever possible
1. const return value for overload function
class
Rational; const
Rational operator*( const
Rational &lhs, const
Rational &rhs); |
this kind of code can prevent error like this
Rational a, b, c; (a*b) = c; |
I know that you want to use "==" other than "=", but compiler would happily generate code for you and maybe you spend hours to debug. All you need to do is define return value const.
2. const member functions
Let‘s see an example
class
TextBlock { public : ... const
char & operator[](std:: size_t
position) const
{ return
text[position]; } char
& operator[](std:: size_t
position) { return
text[position]; } private : std::string text; }; |
and then to illustrate how const member function works
std::cout << tb[0]; // Fine call non-const TextBlock tb[0] = ‘x‘ ; // Fine write non-const TextBlock std::cout << ctb[0]; // Fine read const TextBlock ctb[0] = ‘x‘ ; //error |
Be careful that non-const version operatpr[] returns a reference to char not char itself. If member function do return a char, then compile will report error when interpring tb[0] = ‘x‘, because you can‘t change an internal type (char, int, double..). And even compile successfully, tb[0] is just a copy of original object, that won‘t be what you want.
3. To avoid duplication code in const and non-const member functions
Typically, corresponding const and non-const have similar functions, and to avoid duplications, we make non-const version of member function call const version with certain cast
class
TextBlock { public : ... const
char & operator[](std:: size_t
position) const
{ ... return
text[position]; } char
& operator[](std:: size_t
position) { ... return
const_cast < char
&> ( static_cast < const
TextBlock&> (* this )) [position]; } private : std::string text; }; |
As you can see, above has two casts, not one. We want the non-const member function call const member function. But if inside the non-const [] we call [], we recursivly call ourselves. So we need to cast (*this) to const first, and then const_cast is used to remove const of return value
4. Use mutable keyword to remove non-static variable of the constaints of constness
class
TextBlock { private : std::string text; mutable
std:: size_t
len; }; |
Now mutable can be changed inside a const member function
Effective C++ Item 3 Use const whenever possible,古老的榕树,5-wow.com
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。