GuruoftheWeek#6:正確使用const

字號:

問題:
     const是寫出更安全的代碼的一個利器.而且它還可以幫助編譯器進(jìn)行優(yōu)化.應(yīng)該盡可能的多用...但是什么才叫做"盡可能"呢?
     不對下面程序的結(jié)構(gòu)和其他風(fēng)格問題作挑剔,因為它僅僅是用來做示例說明.請只在合適的地方簡單的加上或刪除"const"(包括一些變量和相關(guān)的關(guān)鍵字).附加題是:哪些地方將使程序由于const的錯誤使用而產(chǎn)生編譯錯誤或不確定的(undefined)結(jié)果?
     class Polygon {
     public:
     Polygon() : area_(-1) {}
     void AddPoint( const Point pt ) {
     InvalidateArea();
     points_.push_back(pt);
     }
     Point GetPoint( const int i ) {
     return points_[i];
     }
     int GetNumPoints() {
     return points_.size();
     }
     double GetArea() {
     if( area_ < 0 ) // if not yet calculated and cached
     CalcArea(); // calculate now
     return area_;
     }
     private:
     void InvalidateArea() { area_ = -1; }
     void CalcArea() {
     area_ = 0;
     vector::iterator i;
     for( i = points_.begin(); i != points_.end(); ++i )
     area_ += /* some work */;
     }
     vector points_;
     double area_;
     };
     Polygon operator+( Polygon& lhs, Polygon& rhs ) {
     Polygon ret = lhs;
     int last = rhs.GetNumPoints();
     for( int i = 0; i < last; ++i ) // concatenate
     ret.AddPoint( rhs.GetPoint(i) );
     return ret;
     }
     void f( const Polygon& poly ) {
     const_cast(poly).AddPoint( Point(0,0) );