Here is my problem, the problem is in comments
const int a = 5;
const_cast<int&>(a)=7; //throw over const attribute in a,and assign to 7
std::cout<<a<<std::endl; //why still out put 5!!!!!!!!!!
Who can tell me why, and some books account these problems to recommend ? Thanks!
As-written the way you're doing this is undefined behavior. If you wanted to see the effects of
const_cast<>
in a defined manner:The only reason this is defined behavior is due to the non-const nature of the original variable,
a
. You cannot take an outright-const object and simply cast away the const-ness, which is what your posted code did. (at least as it has been explained to me on several occasions).