Reputation: 855
I have a struct like this
struct S {
int l;
double* very_large_data;
}
On this struct I want to act upon various functions. In particular there are some function for which I want an instance of S to be read only. However if I define
int read_only(const struct S* S_ptr) {
...
*very_large_data = ... // OK, no error
...
}
inside the function I can always access and modify the value of data pointed by very_large_data
. In order to prevent this one can of course modify the struct definition to
struct S {
int l;
const double* very_large_data;
}
in that way is not possible to to modify data even if the structure is passed as non const pointer
int write_on_S(struct S* S_ptr) {
...
*very_large_data = ... // ERROR, this is a pointer to const.
}
in this way one would be forced to reallocate the pointer to modify the data. This would require possibly very large operations with memory.
Which would be the best design to enforce "logical" const correctness without introducing some costly memory operations?
Upvotes: 1
Views: 67
Reputation: 134008
You could always cast away the const
inside your function, i.e.
int write_on_S(struct S* S_ptr) {
double *data = (double *)S->very_large_data;
*data = 42.0;
}
This is valid provided that very_large_data
did not point to an actually const
-qualified object.
Upvotes: 1