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
{
public:
MyClass();
int getSomething() const;
private:
int* data;
};
// ... data = new int[10];, or whatever
int MyClass::getSomething() const
{
data[4] = 3; // this is allowed, even those the function is const
return data[4];
}
I’d prefer if this was not allowed. How should I define “data” so that “getSomething() const” isn’t allowed to change it? (but so that non-const functions are allowed to change it.) Is there some kind of “best practice” for this? Perhaps std::vector?
In a
constmember function, the type ofdatachanges fromint*toint *const:which means, it’s the pointer which is
constin the const member function, not the data itself the pointer points to. So you cannot do the following:as it’s attempting to change the pointer itself which is const, hence disallowed, but the following is allowed:
Because changing the content doesn’t change the pointer.
datapoints to same memory location.If you use
std::vector<int>, then you can achieve what you want. In fact, vector solves this problem, along with the memory management issues, therefor use it: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: