Preventing a const member function from changing a member array

前端 未结 3 520
时光取名叫无心
时光取名叫无心 2021-01-14 15:14

Apparently, a const member function is still allowed to change data that the class member are pointing to. Here\'s an example of what I mean:

class MyClass
{         


        
3条回答
  •  孤独总比滥情好
    2021-01-14 15:54

    In a const member function, the type of data changes from int* to int *const:

    int * const data;
    

    which means, it's the pointer which is const in the const member function, not the data itself the pointer points to. So you cannot do the following:

    data = new int[100]; //error 
    

    as it's attempting to change the pointer itself which is const, hence disallowed, but the following is allowed:

    data[0] = 100; //ok
    

    Because changing the content doesn't change the pointer. data points to same memory location.

    If you use std::vector, then you can achieve what you want. In fact, vector solves this problem, along with the memory management issues, therefor use it:

    class MyClass
    {
    public:
      MyClass();
      int getSomething() const;
    private:
      std::vector data;
    };
    
    MyClass::MyClass() : data(10) {}  //vector of size 10
    
    int MyClass::getSomething() const
    {
      data[4] = 3; // compilation error - this is what you wanted.
      return data[4];
    }
    

    Avoid non-RAII design as much as you can. RAII is superior solution to memory management issues. Here, with it, you achieve what you want. Read this:

    • Resource Acquisition Is Initialization (RAII)

提交回复
热议问题