Boost logo

Boost Users :

From: Mark Sizer (boost_at_[hidden])
Date: 2003-10-22 11:45:07


Richard Damon wrote:

>>-----Original Message-----
>>From: boost-users-bounces_at_[hidden] [mailto:boost-users-
>>bounces_at_[hidden]] On Behalf Of Mark Sizer
>>Sent: Tuesday, October 21, 2003 10:04 PM
>>To: boost-users_at_[hidden]
>>Subject: [Boost-users] Re: Condition variable and const-correctness
>>
>>I say that the difference between physical const and logical const is
>>EXACTLY what you are saying it is: A logically const method does not
>>change the internal state of the object. A phyically const method does
>>not modify any members of the object. A phyically const method is
>>necessarily logically const. The converse may not be true. The
>>distinction is that a logically, but not physically, const method
>>requires "mutable" member variables to compile.
>>
> Actually a physically const method might not be logically const. Take for
> example a string class which has a pointer to a buffer which holds the
> string (plus maybe some other bookkeeping members). The data pointed to is
> logically part of the object but is not physically part of it. A physically
> const method may not change the pointer, but is allowed to change the data
> pointed to by the pointer as this data is not "physically part of the
> object", but such an operation is not logically const.
>

Ooops. You are correct. I consider this a language bug. Take the following:

class A
{
   public:
     const int& rkiValue() const
       { return _iValue; }
     void Value( const int& rkiNew )
       { _iValue = rkiNew; }
   private:
     int _iValue;
};

class B
{
   public:
     B(A* paForMe) :
       _paMine(paForMe)
       { ; }

     const A& rkaMine() const
       { return *_paMine; }
     A& raMine()
       { return *_paMine; }

     // this is const-correct
     const int& rkiAValue1() const
       { return rkaMine().rkiValue(); }

     // this will not compile
     const int& rkiAValue2() const
       { return raMine().rkiValue(); }

     // this will compile, even though it's IDENTICAL to the above
     const int& rkiAValue3() const
       { return _paMine->rkiValue(); }

     // this will not compile
     void SetValue1( const int& rkiNew ) const
       { raMine().Value(rkiNew); }

     // this will compile, even thought it's identical to the above
     void SetValue2( const int& rkiNew ) const
       { _paMine->Value(rkiNew); }

   private:
     A* _paMine;
};

In order to get any reliable help from the compiler with
const-correctness, one must ALWAY use accessors. Otherwise that pointer
case just slips through. Of course, code reviews can catch it.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net