c++ - 为什么 int 指针的 const vector 中的取消引用元素是可变的?

标签 c++ pointers vector constants operator-precedence

我不确定const vector<int *>的真正含义所以我编译了下面的代码以获得一个想法,但现在更加困惑了。

vector<int *> v;
int x = 1, y = 2;
v.push_back(&x);
v.push_back(&y);

const vector<int *> w = v;
w[0] = &y;   //failed. Element is a constant pointer?
*(w[0]) ++;  //failed. Element pointer references to constant value?

如果我停在这里,我会假设 const vector<int *>const int * const 的 vector ,但后来我尝试了以下显然与该假设相矛盾的方法。

*(w[0]) += 3; //passed. Value not constant?
*(w[0]) = 20; //passed. Why...

现在 *(w[0])出于我不知道的原因,显然对待 +++=和分配不同。我说服自己 const vector仅声明 vector 的常量对象类,并且上述结果可能取决于 vector 的运算符重载的实际实现类(class)。但我无法解决这个问题。谁能帮忙解释一下?

如果相关,我在 Mac 上使用了 g++ 4.2。

最佳答案

Why is dereferenced element in const vector of int pointers mutable?

对于 const vector<int *> , 元素将是 const指向非 const 的指针,即 int * const , 所以你可以修改指针指向的对象,但不能修改指针本身。

根据Operator Precedence , 后缀自增运算符的优先级高于 operator* , 所以 *(w[0]) ++;相当于

* ((w[0]) ++);

首先对指针进行递增,然后失败。 w[0] = &y;也在尝试修改指针,所以也失败了。

另一方面,(*w[0]) ++; (即增加指针)会很好。以下语句也很好,因为它们都在修改指针指向的对象,而不是指针。

*(w[0]) += 3; //passed.
*(w[0]) = 20; //passed.

关于c++ - 为什么 int 指针的 const vector 中的取消引用元素是可变的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46110797/

相关文章:

c++ - C++中枚举的字符串

C 错误 : cannot take the address of an rvalue of type 'void'

c++ - 在 C++ 中,如何存储 SQL 查询并对其进行排序?

c++ - Qt删除QTableView中选中的行

c++ - std::ostream::operator<< 没有为 std::string 定义?

c - (C) 函数之间和函数内——指针

c++ - 将 vector<string> 作为函数参数传递时出现问题 C++

c++ - 来自具有相同基类的多个类的元素 vector

c++ - 没有运算符 << 匹配这些操作数

c++ - 全局指针变量如何存储在内存中?