const_cast在C ++中的行为 [英] behavior of const_cast in C++
问题描述
这是我的问题,问题是在注释
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!
推荐答案
如果你这样做的方式是未定义的行为。如果您想以定义的方式查看 const_cast<>
的效果:
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:
int a = 5; // note: not const. regular object.
const int& cref = a; // const-reference to same object.
cref = 7; // illegal. cref is a const reference.
const_cast<int&>(cref) = 7; // legal. the original object a is not const.
只有 的原因是定义的行为是由于非const原始变量的性质, a
。你不能接受一个直接的const 对象,只是抛弃的常量,这是你的代码做的。 (至少已经多次向我解释过)。
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).
这篇关于const_cast在C ++中的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!