数组作为const指针

Ash*_*ban 6 c++ arrays pointers

请考虑以下代码:

void Increment(int *arr) {
    arr++;
}

int main() {
    int arr[] = {1,2,3,4,5};
    // arr++  // illegal because its a const pointer
    Increment(arr);   // legal
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果arr是一个const指针,我怎么能把它发送到一个没有接收到const指针的函数?

代码编译时没有丢弃const限定符的警告.

Pra*_*rav 10

我的问题是如果arr是一个const指针,我怎么能把它发送到一个没有接收到const指针的函数?

arr(内部main())不是const指针,它是一个数组.传递给函数时,数组类型会衰减为指针类型.

arr(parameter)inside Increment保存参数地址的副本arr(由value传递main()).

// arr ++ // ileagal因为它是一个const指针

这是非法的,因为它是arr不可修改的lvalue.


MSa*_*ers 7

不要被指针迷惑.普通投注也是如此:

const int a = 42;
int b = a; // How can I assign a const int to a non-const int?
int c = 4; // Come to think of it, the literal 4 is a constant too
void foo (int x) { std::cout << x; }
foo(a); // How come I can call foo with a const int?
Run Code Online (Sandbox Code Playgroud)

总之,const单独应用于每个对象.const对象的副本也不需要是const.