简体   繁体   English

为什么我们可以在 C++ 中增加指向常量数据的解引用指针?

[英]why can we increment the dereferenced pointer to a constant data in C++?

I was surprised that c++ allows incrementing dereferenced pointer to a constant data, which it should not allow through a pointer to a const data.我很惊讶 c++ 允许增加指向常量数据的解引用指针,它不应该允许通过指向常量数据的指针。 Consider the code:考虑代码:

#include<iostream>
#include<climits>
using namespace std;

int main(){
    int x = 2;

    const int *xPtr2 = &x;
    *xPtr2++;
    cout << x << endl;

}

But still the value of x is 2. That means *xPtr2 was not actually incremented.但是 x 的值仍然是 2。这意味着 *xPtr2 实际上并没有增加。 I also tried *xPtr2 = 3, but this time it shows compilation error.我也试过*xPtr2 = 3,但这次它显示编译错误。 Why is it so?为什么会这样?

Here the precedence of ++ is more than that of *. 在这里,++的优先级比*的优先级高。 Hence 因此

*xPtr2++

is equivalent to 相当于

*(xPtr2++)

Since xPtr2 is not a constant pointer but a pointer to constant data, incrementing xPtr2 and dereferencing it is fine in this case (but not others) and hence no compilation error is caused. 由于xPtr2不是常量指针,而是指向常量数据的指针,因此在这种情况下(而不是其他情况)可以增加xPtr2并对其进行解引用是可行的,因此不会引起编译错误。

The increment has a higher precedence than does dereferencing. 增量的优先级高于取消引用的优先级。 So you are incrementing the pointer then dereferencing the incremented pointer. 因此,您要先递增指针,然后再取消引用递增的指针。 The pointer is not constant so it can be incremented. 指针不是恒定的,因此可以递增。

The ++ operator has precedence over dereferencing. ++运算符优先于解引用。 Basically you're dereferencing the pointer that has been incremented. 基本上,您要取消引用已递增的指针。

For the behavior you're trying to accomplish, you should wrap the pointer in parens. 对于您要完成的行为,应将指针包装在括号中。

(*xPtr2)++;

Same goes for assigning - you're trying to assign an int to a int * . 分配也一样-您正在尝试将int分配给int * It would work with parens. 它可以与原谅。

(*xPtr2) = 3;

See your example in ideone . 在ideone中查看您的示例

You have mentioned 你已经提到

dereferencing pointer to constant data 解引用指向常量数据的指针

So, lets consider the following code 因此,让我们考虑以下代码

#include <stdio.h>
int main() {
    const int foo = 0xdead;
    int* bar = (int*) &foo;
    *bar = 0xcafe;
    printf("const int foo = %#x", foo);
    return 0;
}

Output : const int foo = 0xcafe 输出: const int foo = 0xcafe

In C, C++ const is just a compile time modifier for variables. 在C中,C ++ const只是变量的编译时修饰符 This means that the compiler wants no modification to a const at compile time. 这意味着编译器在编译时不希望对const进行任何修改。 At runtime there is no concept of const => all local variables are stored in stack, all static and global variables are stored in .data section. 在运行时,没有const =>的概念,所有局部变量都存储在堆栈中,所有static和全局变量都存储在.data节中。 Thus you can dereference a const and modify it only at runtime 因此,您可以取消引用const并仅在运行时对其进行修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM