首页 > 解决方案 > Const robustness of pointer inside a struct and performance

问题描述

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?

标签: cdata-structuresconst-correctness

解决方案


你总是可以抛弃你的const功能内部,即

int write_on_S(struct S* S_ptr) {
    double *data = (double *)S->very_large_data;
    *data = 42.0;
}

very_large_data如果没有指向实际const限定的对象,这是有效的。


推荐阅读