Perhaps I have misunderstood your problem, but I thought you asked for a
reference to an int pointer...
Sorry I misunderstood. Remember, a
reference is different than a pointer in some subtle ways, particularly when you start playing with address-of operators.
What you are asking for is a pointer to a pointer variable, then to perform indirection through that value. That is
+-------+ +------+
| alias |-->| ptr1 |-->something
+-------+ +------+
const mutable
That is: 'alias' cannot be modified or used to modify anything, whereas 'ptr1' can be modified however you like.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream>
using namespace std;
int main()
{
int v1 = 42;
int v2 = -7;
int* ptr1;
typedef const int* cintptr;
const cintptr* const alias = &ptr1;
ptr1 = &v1;
cout << "value = " << **alias << endl;
ptr1 = &v2;
cout << "value = " << **alias << endl;
#if 0
// prove that **alias cannot be modified
**alias = 12;
cout << "value = " << **alias << endl;
#endif
#if 0
// prove that *alias cannot be modified
int v3 = 123;
*alias = &v3;
cout << "value = " << **alias << endl;
#endif
#if 0
// prove that alias cannot be modified
int v4 = 234;
int* ptr2 = &v4;
alias = &ptr2;
cout << "value = " << **alias << endl;
#endif
return 0;
}
| |
Notice that you now have to remember to doubly-indirect 'alias' to get to the value. Your code can directly modify 'ptr1' however it likes, and the user's code cannot modify anything... it must still access stuff through 'alias'.
Keep in mind that C and C++ were not designed to provide purely
const objects -- you can always cast away the constness and modify things. The only way to get around this is to use the processor's memory management directly to catch attempts toward illegal accesses and modify the attempt yourself. There are some libraries (designed for debugging out-of-bounds array accesses and the like) that do this kind of thing, but the overhead probably isn't worth it.
The only obvious answer to get around it would be to write a class to stand-in for 'alias', much like the STL iterators. I'll come back with an example a little later.
Hope this helps.