In c++, if a member pointer point to some data, how to protect that data from being modified? -
class { public: a(){ val = 0; p = new int; *p = 0; } //void fun_1()const{ val = 1; } not allowed void fun_2()const{ *p = 1; } void display()const{ cout<< val <<' '<< *p <<endl; } private: int val; int * p; }; int main() { const a; a.fun_2(); }
change member data in const member function fun_1()const
not allowed. however, when data not directly member of object, allocated storage , assigned inside object, const function can't protect it. fun_2()const
can change data p
point although it's const function example.
is there way protect data p
point ?
it's relatively straightforward cause compiler protect pointed-to object, not done automatically because isn't correct thing do.
template<typename t> class constinator_ptr { t* p; public: explicit constinator_ptr( t* p_init ) : p (p_init) {} t*& ptr() { return p; } // use reassign, or define operator=(t*) t* operator->() { return p; } const t* operator->() const { return p; } t& operator*() { return *p; } const t& operator*() const { return *p; } };
just use in place of raw pointer, this:
class { public: a() : val{0}, p{new int(0)} {} //void fun_1()const{ val = 1; } not allowed void fun_2()const{ *p = 1; } // causes error void display()const{ cout<< val <<' '<< *p <<endl; } private: int val; constinator_ptr<int> p; };
Comments
Post a Comment