|
-
June 20th, 2009, 08:30 AM
#16
Re: read only alias to a pointer
Firstly thanks to all of you for coming up with a lot work around methods.
JVene - I am having a look at your implementation, give me some time, I will come back on that, thanks.
Artella, thanks for that idea, it seems like a possibility as well, just feel it is a little risky (I could be completely wrong, correct me if I am wrong)
The idea of casting a "const int*" to a "int *" seems a little risky and wrong to me, again I could be wrong.
The reason I feel that way is because, const int* is not supposed to change the value of the variable it points to. So attempting to do so doesn't seem correct.
I know your original program has managed to do this successfully.
However I feel if you change the variable v1 to a const int variable, it might present a problem
Changes to your program
-------------------------------
I had done some changes to your program to test it further, changes are mentioned below:
1) to include a more detailed cout statement (to include address of variables and pointers)
2) change the declaration of the variable v1 to "const int".
Code:
#include <iostream>
using namespace std;
int main(void)
{
system("clear");
const int v1 = 10;
int v2 = 20;
cout << "&v1 = " << &v1 << "\tv1 = " << v1 << endl;
cout << "&v2 = " << &v2 << "\tv2 = " << v2 << endl;
cout << "\n\n------------\n\n";
const int* ptr = &v1;
cout << "&ptr = " << &ptr << "\tptr = " << ptr << "\t*ptr = " << *ptr << endl;
cout << "\n\n------------\n\n";
*const_cast<int *>(ptr) = v2;
//*ptr = v2;//This is NOT ALLOWED
cout << "&ptr = " << &ptr << "\tptr = " << ptr << "\t*ptr = " << *ptr << endl;
cout << "\n\n------------\n\n";
cout << "&v1 = " << &v1 << "\tv1 = " << v1 << endl;
cout << "&v2 = " << &v2 << "\tv2 = " << v2 << endl;
cout << "\n\n------------\n\n";
return 0;
}
If you see the output of the program, you will realize, finally *ptr shows the value 20, however the value of the value of the constant v1 remains as 10.
And ptr points to v1.
output (removed some blank lines from the output)
Code:
&v1 = 0xbfffd17c v1 = 10
&v2 = 0xbfffd178 v2 = 20
-----------
&ptr = 0xbfffd174 ptr = 0xbfffd17c *ptr = 10
------------
&ptr = 0xbfffd174 ptr = 0xbfffd17c *ptr = 20
------------
&v1 = 0xbfffd17c v1 = 10
&v2 = 0xbfffd178 v2 = 20
------------
Last edited by Muthuveerappan; June 20th, 2009 at 08:45 AM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|