const modifier on pointer attributes?

Hi,
i have a question related to the const modifier for class methods.
If I have a class like this:

class A
{
int b;

void printToScreen() const;
}

then I know that the printToScreen() method will not modify the b attribute.
But if I have

class A
{
int* b;

void printToScreen() const;
}

then it might as long as the adress b points to does not change.

Is there any way to specify that in this last case the value of b (the integer pointed to) cannot be changed? I am working on a program where almost all class attributes are pointers, and I would like to be able to enforce that the objects pointed to do not change for some methods.

Thanks in advance!


There's no easy way. It's the reason there are both iterators and const_iterators.

The problem is that the const modifier gets placed in the wrong spot for you:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int *p; //pointer to int
int const *p; //pointer to const int
int *const p; //const pointer to int
int const *const p; //const pointer to const int
//...
class blah
{
    int *p; //for const methods this goes to "int const *p;"
    //...
    void dostuff() const
    {//dirty fix:
        int const *const p = this->p; //mask the member p with a temporary
        //...code...
    }
};
It may look easy, but it isn't - when you need to change things around it would easily mess up your code.
Last edited on
thanks,
it is not ideal, but it is something.
thanks again!
You can just create a simple wrapper class with a const dereference operator.
Something like this:

1
2
3
4
5
6
7
8
9
10
template <class T> struct const_abiding_ptr
{
  const_abiding_ptr(T* ptr=0) : ptr(ptr) {}
  
  T& operator*() {return *ptr;}
  const T& operator*() const {return *ptr;}

  private:
    T* ptr;
};
Last edited on
then it might as long as the adress b points to does not change.
As the developer you are in control of the state of b when inside that function, all the const means is you promise to not change b inside that function.
Last edited on
Thanks for all these comments. @Athar, that is a very nice trick. The only drawback I see is that i would have to change the type signature of the methods I want to be const. I will think about it.
The only drawback I see is that i would have to change the type signature of the methods I want to be const.

How so? You only need to change the type of the pointer to const_abiding_ptr<int>, you don't have to touch the methods.
Another drawback is that it will need to be recursive so it works even with an int***
Do you mean like this?

class A
{
const_abiding_ptr<int> b;

void printToScreen() const;
}

Wouldn't that mean that I can never ever modify b from A? The thing is, I would want to be able to modify b from some methods form A but not from others.
It is not const abiding when you do not access it from a const method.
ok, I see that now.
Topic archived. No new replies allowed.