menu

hjk41的日志

Avatar

Effective C++ Note 21: Use const whenever possible

Where to use const?

const char * a; // const data, non-const pointer
char const * a; // same as const char * a
char * const a; // const pointer, non-const data
const char * const a; // const pointer, const data

class C{
  const C operator +( const C & rhs); // const return value
  void f2() const; // const member function
  void f3();  // this member function may change the data member of C
};

Why do we use const?
We use const to constants and function return values because we don't wan't them to be changed, and we use const to functions because we want them to be available on constant classes.

void f1(C & d);
const C a;
f1(a);  // error! And this is exactly what we want

const C b;
b.f3();  // error! b is not supposed to be changed

Consider the following code:

class C{
public:
  float getAverage() const{
    average=(1.0*sum)/n;  // error!
    return average;
  };
private:
  int sum;
  int n;
  float average;
};


If we do want the call getAverage() on a constant C, how do we do it? There are two way to do this.
Solution 1. Declare average as mutable.

class C{
public:
  float getAverage() const{
    average=(1.0*sum)/n;  // fine, mutable variables can be changed 
                                     // in a const member function
    return average;
  };
private:
  int sum;
  int n;
  mutable float average;
};


Solution 2. Use const_cast

class C{
public:
  float getAverage() const{
    C * l=const_cast<C *>this;
    l->average=(1.0*sum)/n;  // also fine
    return average;
  };
private:
  int sum;
  int n;
  mutable float average;
};


However, we shouldn't try to modify an object that is defined to be const, or the result will be undefined.

评论已关闭