Use of 'const' for function parameters

前端 未结 30 2860
借酒劲吻你
借酒劲吻你 2020-11-22 03:06

How far do you go with const? Do you just make functions const when necessary or do you go the whole hog and use it everywhere? For example, imag

30条回答
  •  攒了一身酷
    2020-11-22 03:23

    I know the question is "a bit" outdated but as I came accross it somebody else may also do so in future... ...still I doubt the poor fellow will list down here to read my comment :)

    It seems to me that we are still too confined to C-style way of thinking. In the OOP paradigma we play around with objects, not types. Const object may be conceptually different from a non-const object, specifically in the sense of logical-const (in contrast to bitwise-const). Thus even if const correctness of function params is (perhaps) an over-carefulness in case of PODs it is not so in case of objects. If a function works with a const object it should say so. Consider the following code snippet

    #include 
    
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    class SharedBuffer {
    private:
    
      int fakeData;
    
      int const & Get_(int i) const
      {
    
        std::cout << "Accessing buffer element" << std::endl;
        return fakeData;
    
      }
    
    public:
    
      int & operator[](int i)
      {
    
        Unique();
        return const_cast(Get_(i));
    
      }
    
      int const & operator[](int i) const
      {
    
        return Get_(i);
    
      }
    
      void Unique()
      {
    
        std::cout << "Making buffer unique (expensive operation)" << std::endl;
    
      }
    
    };
    
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    void NonConstF(SharedBuffer x)
    {
    
      x[0] = 1;
    
    }
    
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    void ConstF(const SharedBuffer x)
    {
    
      int q = x[0];
    
    }
    
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    int main()
    {
    
      SharedBuffer x;
    
      NonConstF(x);
    
      std::cout << std::endl;
    
      ConstF(x);
    
      return 0;
    
    }
    

    ps.: you may argue that (const) reference would be more appropriate here and gives you the same behaviour. Well, right. Just giving a different picture from what I could see elsewhere...

提交回复
热议问题