Propagate constness to data pointed by member variables

前端 未结 4 1628
难免孤独
难免孤独 2020-12-14 16:41

It is often quite confusing to C++ newcomers that const member functions are allowed to call non-const methods on objects referenced by the class (either by pointer or refer

4条回答
  •  春和景丽
    2020-12-14 17:02

    One approach is to just not use the pointer directly except through two accessor functions.

    class SomeClass
    {
      private:
        class SomeClassImpl;
        SomeClassImpl * impl_; // PImpl idiom - don't use me directly!
    
        SomeClassImpl * mutable_impl() { return impl_; }
        const SomeClassImpl * impl() const { return impl_; }
    
      public:    
    
        void const_method() const
        {
          //Can't use mutable_impl here.
          impl()->const_method();
        }
        void non_const_method() const
        {
          //Here I can use mutable_impl
          mutable_impl()->non_const_method();
        }
    };
    

提交回复
热议问题