This is related to the (currently) closed question I asked earlier: Can you mutate an object of custom type when it's declared as constant?
Suppose we have something that looks like the following:
class test
{
public:
test() : i{4}, ptr{&i} {};
int i;
int *ptr;
int *get_ptr() const {return ptr;}
};
void func(const test &t, int j) {
*(t.get_ptr()) = j;
// auto ptr = t.get_ptr();
// *ptr = j;
}
int main(int argc, char const *argv[])
{
test t;
std::cout << t.i << std::endl;
func(t, 5);
std::cout << t.i << std::endl;
}
We have this func
that takes in a const test &
. When I see this signature (and if I didn't look at the implementation of the function), it makes me want to assume that nothing in t
will get modified; however, the member variable i
is able to be modified through the ptr
member variable, as we see here.
I don't usually write code that end up working this way, so I'm wondering if code like this is discouraged?
Furthermore, is it reasonable to assume (most of the time) that an object declared as const
will not be mutated?
int *ptr
can point to an internalint
during construction, becauseconst
objects only becomeconst
after construction. Footgun locked and loaded.ptr
member points to). The fact that it points at another member variable is something the compiler won't check.