将const int赋值给指向int的const指针是非法的
Assigning const int to a const pointer to int is illegal?
为什么以下内容是非法的?
extern const int size = 1024;
int * const ptr = &size;
当然,应该允许指向非常量数据的指针指向常量int(而不是相反)?
这来自C++Gotchas项目#18
如果你真的是指
const int * const ptr = &size;
const int * ptr = &size;
这是合法的。你的是违法的。因为它不是你可以做
int * ptr const = &size;
*ptr = 42;
啊,你的惊愕刚刚改变了。
让我们看看另一种方式:
int i = 1234; // mutable
const int * ptr = &i; // allowed: forming more const-qualified pointer
*i = 42; // will not compile
我们不能在这条路上造成伤害。
如果允许指向非一致数据的指针指向const int,则可以使用指针更改const int的值,这将是不好的。例如:
int const x = 0;
int * const p = &x;
*p = 42;
printf("%d", x); // would print 42!
幸运的是,以上情况是不允许的。
相关文章:
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 在C++中,如果"int a = 3; int* p = &a;",那么为什么不允许"const int* &pp = p",但允许"const int* const &pp = p"?
- 调用'myStud::myStud(int, const char [5], int, int, int)'没有匹配函数
- 返回对象时从'const DList<int>* const'到 'DList<int>*' [-fallowive] 的转换无效
- int(int)& 或 int(int) const &是什么类型?
- 传递 const int* 和 int* 时调用重载函数的不同版本(const int* const&/&&)
- 如何在构造函数中初始化int const * const
- 对"displayForStudent(int, int const*, double const*, int)"的未定义引用 collect2.exe:错误:ld 返回 1 个退出状态
- 如何在 C++ 中解释"const int *const & variable"
- 为什么"int & const" MSVC 编译得很好?
- const int const&和const int&in C++有什么区别?
- std::set<int * const> 不会编译
- " invalid operands of types 'int' and 'int* const'" 来自功能的错误,来自书
- std::initializer_list<int const> 不能从 std::initializer_list <int>构造
- 对'std::string Helper::ToString<int>(int const&)'的未定义引用
- 无法弄清楚 int[3][3] 和 int(* const)[3] 之间的区别
- const int* const fun(const int* const& p) const的含义;
- 为什么vector<int * const>是非法/不合逻辑的?
- 对 Stack<int>::p ush(int const&) 的未定义引用
- JsonCpp:未定义的对"Json::Value::operator[](int) const"的引用