简体   繁体   中英

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?

You could always cast away the const inside your function, ie

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM