const methods()

Kristian Kilpi kjkilpi at gmail.com
Tue Jan 23 04:18:42 PST 2007


On Tue, 23 Jan 2007 12:18:28 +0200, renoX <renosky at free.fr> wrote:
> Andrey Khropov Wrote:
>> Frits van Bommel wrote:
>> > the way C++ does const sucks :P.
>> Why?
>
> I remember that this is common knowledge, but I don't remember why.
>
> If memory serves, this is because in C++ you can 'unconst' parameters  
> with a cast, so the compiler cannot really optimise the code.

One thing I hate with C++'s const, sometimes, is that it applies to the  
whole class, not just the part that's visible to the user.

For example:

   class MyClass {
   public:
     int getVal() const {
       update_cache();  //(error, not const)
       return m_cache.val;
     }

   protected:
     void update_cache() {
       if(m_cache.is_dirty) {
         m_cache.is_dirty = false;
         m_cache.val = ...;
       }
     }

     my_cache_t m_cache;
   };

I would like to have different 'layers of constness'. E.g. one layer  
guarantees that a method doesn't alter the public state of the class, the  
second layer that the non-public state is not changed.

In the example above, one have to do an 'unconst' in 'getVal()':

   ((MyClass *)this)->update_cache();

When carefully used it's useful, and necessary for 'greater good'. ;)



More information about the Digitalmars-d mailing list