C++ const method on non const pointer member

后端 未结 4 1088
礼貌的吻别
礼貌的吻别 2020-12-19 10:33

I was wondering how protect a non const pointer member from an object throught a const method. For example:

class B{
    public:
        B(){
            thi         


        
4条回答
  •  离开以前
    2020-12-19 10:53

    Try using the following general approach, to protect the const-ness of objects referenced via pointers, in this situation.

    1. Rename B *b

      B *my_pointer_to_b;
      

      And change the initialization in the constructor accordingly.

    2. Implement two stubs:

      B *my_b() { return b; }
      const B *my_b() const { return b; }
      
    3. Replace all existing references to b with my_b(), in the existing code. Going forward, in any new code, always use my_b() to return the pointer to b.

    Mutable methods will get a non-const pointer to B; const methods will get a const pointer to B, and the extra step of renaming makes sure that all existing code is forced to comply with the new regime.

提交回复
热议问题