Question

I apologize if the title sounds abstruse, let me make that simple with an example :

class A
{
public:
    A(int *flag) : flag_(flag) {}
    void foo();
private:
    void bar();
    int *flag_;
};

The question is: can I prevent this class from changing the value pointed to by flag_?

Note : I'm thinking, maybe I want to write something like const int * flag_, but I do not want to make the value pointed to by flag "irrevocably" constant. In my case, this value is the value of some member variable of some other class, which can be changed.

Thanks for your insights!

Was it helpful?

Solution

const int *flag_; will not modify the constness of the actual variable passed in, it just defines how flag_ can be used. Whatever you pass into A's constructor will not have its constness changed. const isn't a runtime change, it's merely syntax to prevent the coder from accidentally modifying a value. You can do yourself one better and make it const int *const flag_; which will prevent A from modifying *flag_ AND flag_ won't be reassignable.

OTHER TIPS

The question is: can I prevent this class from changing the value pointed to by flag_?

Note : I'm thinking, maybe I want to write something like const int * flag_, but I do not want to make the value pointed to by flag "irrevocably" constant.

So... you want it to be constant... except for when you don't? No, I don't see a solution to that. You, as the class maintaner, can maintain the invariant that flag_ is only changed under X condition(s).

EDIT: I think I misunderstood you. Just make the pointer const (or what it points to const). That doesn't have any affect on the other member variable, it simply controls how field_ is used.

On a side note, is it safe to store the address of this member of another class? What happens if the instance of the other class is moved (stored in any vectors? There are many cases in which it could be moved, invalidating your pointer)? What happens if the instance is allocated with automatic storage duration and goes out of scope? It's fine to store a pointer member if you really need to (do you?), but there are things you need to consider.

Without using const then no you cannot. But if class A declares the flag pointer as const, that should have not affect another class that has a pointer to the same memory location from modifying the value.

The int* flag_, is a private member; Your class's client user can't change flag_ and flag_ pointed to.

Now This is your class . Don't design to write any code like : *flag_=14;

The Scott Meyers's "Effective c++" has a few thing you want to know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top