c++ - 最初宣布为持续困惑

标签 c++ constants const-cast

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/

相关文章:

c++ - 返回 std::string 作为 const 引用

c++ - 使用静态函数初始化 static const int

c++ - 使用 const-cast 通过非常量引用来延长临时的生命周期

c++ - 是否允许在 const 定义的对象上丢弃 const 只要它实际上没有被修改?

c++ - 这个程序中 "&"有什么区别

c++ - 自动扣除部分模板类型

c++ - 字符串类型函数,模板特化使调用统一

c++ - 对指针及其内存地址的混淆

c++ - VC++ 允许为 STL 容器使用 const 类型。为什么?

C++完美转发: why do we need forward() if we can use const_cast()?