const_cast
仅当您强制转换最初是非常量的变量时才是安全的。
文字是最初声明为常量的唯一数据吗?如果没有,任何人都可以举出最初声明的 const 数据场景的例子吗?
const_cast
仅当您强制转换最初是非常量的变量时才是安全的。
文字是最初声明为常量的唯一数据吗?如果没有,任何人都可以举出最初声明的 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