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.
Output: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;
}
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.
