Is this an appropriate use of const qualifiers in C? -


i have simple vector implementation in c, holds array of void*. it's user take care of actual type.

i want 'promise' vector not alter contents, store data as:

struct _vector{     uint32 used;     uint32 size;     const void** arr; }; 

i don't know if it's considered "overdoing it" constness correctness, try maintain const correctness accessors/modifiers:

void vector_add(vector *v, const void* const elem);    void vector_set(vector *v, const uint32 idx, const void* const elem); 

when return element vector, pointer user's data let user modify data being pointed to, casting away constness in internal array.

void* vector_get(const vector *v, const uint32 idx){     if ( idx >= v->used )          exitaterror("vector","array out of bounds");     return (void*)v->arr[idx]; } 

instead of returning const void*, return void* instead. idea internally, want ensure not changing data being pointed to, don't care happens data outside vector.

is considered correct use of const? think it's okay declare data const in 1 place, while having mutable elsewhere. i'm unsure after reading many dogmatic articles claiming never cast away constness, , if casted away, use of const not appropriate begin with.

i want 'promise' vector not alter contents

this c. data structures not have behavior. can define vector data structure such data pointed-to cannot modified via vector, , that's have done. of course, has implications.

i don't know if it's considered "overdoing it" constness correctness, try maintain const correctness accessors/modifiers:

if you're going bother const @ all, means adhere rigorously const-correctness. otherwise, there's not point.

when return element vector, pointer user's data let user modify data being pointed to, casting away constness in internal array.

nope. you've blown it. const-correctness needs or nothing worth anything.

by casting away const, violate contract vector type makes users allowing pointed-to values modified via instance. indirectly so, sure, doesn't matter. moreover, can contribute wider violations of const correctness -- suppose, example, data entered vector const in first place. storing them in data structure ok, provide functions allow them modified (or @ least allow attempt @ that).

you consider using opaque data structure instead of const-qualifying members prevent elements being accessed directly through vectors. ultimately, though, const-correctness require separate data structures , functions vectors contain const data , contain non-const data.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -