c - Choosing const vs. non-const pointer for user data -
consider simple, re-usable library. has object current state, , callback function feed input.
typedef struct context_s context_t; typedef size_t (*getbytes_t) (context_t * ctx, uint8_t * bytes, size_t max); struct context_s { getbytes_t bytefunc; void * extra; // more elements }; void init(context_t * ctx, getbytes_t func); int getnext(context_t * ctx); // calls callback when needs more bytes user might need data callback (like file pointer). library provides functions have 1 pointer:
void setextra(context_t * ctx, void * ext); // may called after init void * getextra(context_t const * ctx); // may called in callback however, if user data constant, require him cast constness away before setting data. change functions take/return const, require cast in callback, if data should not constant.
void setextra(context_t * ctx, void const * ext); void const * getextra(context_t const * ctx); third alternative hide cast inside function calls:
void setextra(context_t * ctx, void const * ext); void * getextra(context_t const * ctx); is idea hide cast in case?
i'm trying find balance usability , type safety. since using void* pointers, lot of safety gone already.
or overlooking worthy of consideration?
the c standard library has similar problems. notoriously, strchr function accepts const char * parameter , returns char * value points given string.
this deficiency in c language: provisions const not support ways in const might reasonably used.
it not unreasonable follow example of c standard: accept pointer const and, when giving calling software, provide pointer non-const, in third example.
another alternative define 2 sets of routines, setextra , getextra use non-const, , setextraconst , getextraconst use const. these enforced @ run-time bit records whether set context const or non-const. however, without enforcement, helpful because make errors more visible in calling code: reading code see setextraconst used set data , getextra (non-const) used data. (this might not if calling code convoluted , uses const data in cases , non-const data in others, better catch more errors fewer.)
Comments
Post a Comment