const_cast
is safe only if you're casting a variable that was originally non-const.
文字是唯一最初声明为常量的数据吗?如果没有,谁能举例说明最初声明的 const 数据场景?
最佳答案
不,不只是文字最初被声明为常量。 任何声明为 const 的对象“本来就是 const”。
const int this_is_a_const_int = 10;
const std::string this_is_a_const_string = "this is a const string";
std::string this_is_not_a_const_string;
std::cin >> this_is_not_a_const_string;
const std::string but_this_is = this_is_not_a_const_string;
不是最初的 const 是当你有一个对非 const 对象的 const 引用时
int n;
std::cin >> n;
const int & const_int_ref = n;
int& int_ref = const_cast<int&>(const_int_ref); // this is safe, because const_int_ref refers to an originally
// non-const int
关于c++ - 最初宣布为持续困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24400312/