|
-
March 1st, 2004, 03:47 AM
#1
const_cast's (again)
Some of the previous threads about const_casts have left me wondering about something. So I wrote the following little test program, the output of which surprised me a little.
Code:
#include <iostream>
void increment( int& n )
{
++n;
}
int main()
{
int i = 1;
std::cout << i << " - ";
increment( i );
std::cout << i << "\n";
const int j = 1;
std::cout << j << " - ";
// The following does not compile
// int l = const_cast<int>( j );
int * pj = const_cast<int*>( &j );
increment( *pj );
std::cout << j << "\n\n";
return 0;
}
Output:
1 - 2
1 - 1
Does const_cast create a copy of the object? Or is this what "undefined behavior" stands for?
Let me know if other compilers (I'm using g++) create different results.
-
March 1st, 2004, 04:28 AM
#2
const_cast
Hello ,
The out put u can't say wht exactly it will come tht behavoir is called Undefined behavior
 sivakumar
-
March 2nd, 2004, 12:45 AM
#3
Re: const_cast's (again)
I'll try answering this with entire words and complete sentences.
Originally posted by treuss
Does const_cast create a copy of the object? Or is this what "undefined behavior" stands for?
Let me know if other compilers (I'm using g++) create different results.
This is a completely invalid thing to do. A const POD item will not likely exist in normal variable space. At best, you are modifying non-modifyable memory. Even worse, a compiler could do away with this definition completely so that it takes up 0 memory.
Of course, it's compiler dependent. The behavior is indeed undefined.
Jeff
-
March 2nd, 2004, 01:38 AM
#4
Hi,
To be precise the problem is in the statement
You are passing some temporary variable to the increment function.
And n (in increment) would now be an alias to this variable and not *pj.
Thus this seems to me as a defined behaviour as far as value of *pj is concerned, since there is no reason that it should change.
Regards,
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
|