This builds off of my previous question: Is this an appropriate use of const qualifiers in C?
In Vector.h
:
typedef struct _Vector Vector;
Vector* vector_init(const UInt32 size);
void* vector_get(const Vector *v, UInt32 idx);
void vector_add(Vector *v, void* const elem);
void vector_set(Vector *v, const UInt32 idx, void* const elem);
...etc
In Vector.c:
struct _Vector{
UInt32 used;
UInt32 size;
void** arr;
};
Vector* vector_init(const UInt32 size){
Vector* v = malloc(sizeof(Vector));
v->used = 0;
v->size = size;
v->arr = malloc(size*sizeof(void*));
return v;
}
void* vector_get(const Vector *v, const UInt32 idx){
if ( idx >= v->used )
exitAtError("Vector","Array out of bounds");
return v->arr[idx];
}
void vector_add(Vector *v, void* const elem){
if( v->used == v->size )
vector_resize(v);
v->arr[v->used++] = elem;
}
...etc
I want to prevent void** arr
in _Vector
from being accidentally modified by my implementation, as a warning/error at compile time. I can't make arr
a const void**
because I don't want the vector to be permanent, and want to avoid casting away constness.
The idea here is that used
and size
are data that are directly related to the scope of my functions, whereas arr
is just a kind of metadata that I don't want to modify. arr
is opaque, so I can't directly modify it, but I can cast it or directly overwrite in bad ways such as memcpy
.
In this example it seems unnecessary to enforce this access since each function is straight-forward, but this example mostly for demonstration purposes.
I have two related questions that can be answered at the same time:
I see a related question was asked in: Is there a way to protect a class variable from being modified outside of a function
That user seems to be in a similar predicament in C#; my question #2 is relevant in that scenario.
EDIT: I think from everyone's input, it's becoming clear that I'm pushing the language outside of its original design by looking for some type of magical keyword to document things for me. Either hiding my data behind another abstraction, or structurally separating out my functionality to prevent the temptation to poke at the data, seems to be the best solutions.
Since you were looking for a solution either in C/C++, I created a layer of abstraction in C++ to protect the void** const arr
as follows. Please check does it meet your requirement.
class array{
public:
void setArray(void** key)
{
arr=key;
}
void** getArray()
{
return &(*arr);
}
private:
void** arr;
};
struct Vector: public array{
int used;
int size;
};
Vector* vector_init(const int size){
Vector* v =(Vector*) malloc(sizeof(Vector));
v->used = 0;
v->size = size;
void** tem=v->getArray();
tem=(void**) malloc(size*sizeof(void*));
v->setArray(tem);
return v;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments