I'm writing an access function which returns a pointer to an internal buffer and I'd like to hint to users of my function that they shouldn't update the object that's pointed to. A very contrived example would be:
void myAccessFunc(bool string, void* p, size_t* len)
{
static const char* s = "aha!";
static const int i = 123;
if (string)
*(char**)p = &s;
*len = strlen(s);
else
*(int**)p = &i;
*len = sizeof(i);
}
char* s;
size_t bytes;
myAccessFunc(true,&s, &bytes);
printf("Got '%s'\n", s);
Yes, I know that looks flakey.
What I want to prevent is:
char* s;
size_t bytes;
myAccessFunc(true,&s,&bytes);
s[4] = '?';
I know I can't completely prevent it but I'd at least like the compiler warning to hint to a user that they shouldn't be doing that. If they cast my pointer, then that's their problem. Is there some combination of const and void and * that will do this? I tried something like:
void myAccessFunc(bool string, const void** p, size_t* len);
but it seemed do away with the voidness of the pointer so a caller had to do:
const void* p;
size_t bytes;
myAccessFunc(true, &p, &bytes);
or
const char* s;
size_t bytes;
myAccessFunc(true, (const void**)&s, &bytes);
and couldn't do:
const int * ip;
const char* s;
size_t bytes;
myAccessFunc(true, &s, &bytes);
myAccessFunc(false, &i, &bytes);
I finally came around to:
const void* myAccessFunc(bool string, size_t* len);
and if the user does:
char* p = myAcccessFunc(true,&bytes);
the compiler (GCC, at least), does complain about throwing away the qualifier.