If I have a struct in C++ containing dynamically allocated arrays, for example:
typedef struct foo {
int* p;
} foo;
foo aFoo;
aFoo.p = new int[n];
for(int i = 0; i < n; ++i)
aFoo.p[i] = 0;
How can I pass it by reference to a function so that the values stored in aFoo.p[]
cannot be modified by the function?
If I declare int func(foo const& aFoo) { ... }
, I get a compiler error if I try to modify the pointer aFoo.p
, but not if I try to modify, for example, aFoo.p[0]
. I'm also allowed to assign a new pointer int* p2 = aFoo.p
and modify the values of aFoo.p[]
through that.
If I were just passing the pointer, I believe this would be the difference between passing int* const& p
and const int* const& p
, but I'm not sure how to do it in this situation without declaring member p
as a const int*
in the struct definition (which would cause complications in other parts of the code).
As you have noticed: the pointer cannot be modified, but the contents can.
If you want to keep pointers, I suggest getter/setter: