Is this approach for constant pointers ok?

I want to provide different levels of 'const' access to my data. For example, depending on whether the pointer or data should be changed. So this is what I came up with:

class MyClass
{
    int n;
    int* ptr_to_data;
    int* const const_ptr_to_data;
    const int * ptr_to_const_data;
public:
    MyClass(int nn) 
        : n(nn),
          ptr_to_data(&n),
          const_ptr_to_data(ptr_to_data),
          ptr_to_const_data(ptr_to_data)
    {
    }
    ~MyClass() { }

    int& get_data()
    {
        return *const_ptr_to_data;
    }

    const int& get_data() const
    {
        return *ptr_to_const_data;
    }
};

      

The goal is to avoid programmer errors by limiting as much access as possible. Is this a good approach, how to make it better?

+3


source to share


2 answers


The pointers you store do not help with the access issue, as you will see, but they will refer to data in the wrong instance when you copy the object, unless you take responsibility for the copy. And the top level const

prevents the assignment of class instances. That is, pointers are problematic and offer no benefit.

Instead, do the following:

int data() const
{
    return n_;
}

void set_data( int const value )
{
    n_ = value;
}

      

Or, you can do as in the standard library and name the installer as well data

, but the imperative form is more readable in the calling code.




The key feature of this approach is not passing a pointer or reference to a <data item const

.

Because by passing an unrestricted reference or pointer, you lose all control over changes to this data element, in particular with regard to maintaining the class invariant, possibly other related values, introducing range constraints, validation on changes, etc.

+2


source


You have the right two-function approach get_data

, but all pointers just make the code harder to maintain. It's just enough:



int& get_data() { return n; }
const int& get_data() const { return n; }

      

+6


source







All Articles